问题是:在这个特定示例中,如何让 GORM 生成左连接而不是内连接?
试验台:
给定 A、B 和 C 类:
class A{
B someObject
}
class B{
C importantObject
}
class C{
boolean interestingFlag
}
我想列出 A 类的所有元素:
- 他们的 BC 对象为空或
- 他们的 BC 对象interestingFlag 值为 false
到目前为止我尝试了什么:
这种方法产生正确的 A 列表,其中 BC 为空(条件 2 已注释掉)或正确的 A 列表,其中 BCinterestingFlag = false(无论条件 1 是否被注释掉)。当两个条件都未注释时,它只返回一个元素列表,其中 ABCinterestingFlag = false (ABC = null 条件被忽略)
// approach 1 (conditional 1 is ignored)
def result = A.withCriteria{
someObject{
or{
isNull('importantObject') // conditional 1, works well when conditional 2 is commented out
importantObject{
eq('interestingFlag', false) // conditional 2, works well alone, discards conditional 1 when both of them are uncommented
}
}
}
}
编辑:根据评论中的要求,我正在粘贴休眠生成的 sql:
Hibernate: select this_.id as id1_2_, this_.version as version1_2_,
this_.some_object_id as some3_1_2_, someobject1_.id as id2_0_,
someobject1_.version as version2_0_, someobject1_.important_object_id as
important3_2_0_, importanto2_.id as id0_1_, importanto2_.version as version0_1_,
importanto2_.interesting_flag as interest3_0_1_ from a this_
inner join b someobject1_ on this_.some_object_id=someobject1_.id
inner join c importanto2_ on someobject1_.important_object_id=importanto2_.id
where ((someobject1_.important_object_id is null or (importanto2_.interesting_flag=?)))
当我直接将它复制并粘贴到 pgAdmin 查询工具中并更改了一些内容(内部联接更改为左联接,并提供了interestingFlag = "false" 参数)时,一切都按我想要的方式工作(我得到了 ABC = null 和 ABCimportantFlag =虚假对象)
Hibernate: select this_.id as id1_2_, this_.version as version1_2_,
this_.some_object_id as some3_1_2_, someobject1_.id as id2_0_,
someobject1_.version as version2_0_, someobject1_.important_object_id as
important3_2_0_, importanto2_.id as id0_1_, importanto2_.version as version0_1_,
importanto2_.interesting_flag as interest3_0_1_ from a this_
left join b someobject1_ on this_.some_object_id=someobject1_.id
left join c importanto2_ on someobject1_.important_object_id=importanto2_.id
where ((someobject1_.important_object_id is null or (importanto2_.interesting_flag=false)))