我在两个Grails实体之间有一个简单的一对一关系,如下所示:
class Parent {
static hasOne = [child: Child]
}
class Child {
Parent parent
}
问题是,当加载父实体(例如,使用def parent = Parent.first()
)时,可以从数据库中选择子对象,同时在休眠调试日志中可以看到第二个查询,尽管根据the documentation,单端关联应通过以下方式延迟获取:默认。同样,使用上述文档中的lazy: true
映射配置显然也不会改变任何内容。在子代中使用
static belongsTo = [parent: Parent]
时,情况相同。This issue(当前打开)描述了相同的行为。
那么有什么方法可以阻止获取 child 协会吗?
理想情况下,我想应该要么使用带有join的单选来获取它,要么根本不选择它(或者在第一次访问 child 时),最好由开关控制或在HQL查询中使用
fetch join
来获取它。
最佳答案
Optimally, I imagine it should be either fetched using a single select with join or not selected at all (or upon first access of the child), preferrably controlled by a switch or using a fetch join in a HQL query.
可以通过一次选择来获取它。
https://github.com/grails/gorm-hibernate5/issues/136上的问题链接到https://github.com/alanbino/gorm-hasone上的示例项目。我将其 fork 给https://github.com/jeffbrown/gorm-hasone并进行了更改。
https://github.com/jeffbrown/gorm-hasone/commit/32cb943cbc27deb5ebf164aa1461b3956285fe1d上的提交演示了如何单次选择获取数据。提交将配置连接...
static mapping = {
table 'a_parent'
id generator:'assigned'
aChild fetch: 'join'
}
随后在https://github.com/jeffbrown/gorm-hasone/commit/575ae2152767ded30686cb2e3daa70519f03c8ba上提交的内容与这里的问题并不真正相关,但是消除了与该问题无关的许多复杂性,并且消除了这些复杂性,从而使评估代码变得更加容易。忽略这是否会分散注意力。
关于grails - 有没有一种方法可以懒惰地使用hasOne子项获取GORM实体?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64362726/