我使用Grails 2.2.4(Grails 2.3.11中的相同行为)并具有引用域类B的域类A.
class A {
static hasOne = [b: B]
static constraints = { b nullable: true }
}
class B {
static belongsTo = [a: A]
}
Run Code Online (Sandbox Code Playgroud)
我试图找到有B的所有A实例.
A.findAllByBIsNotNull()*.b
Run Code Online (Sandbox Code Playgroud)
返回B和null的列表:
[null, null, b1, b2, null, ...]
Run Code Online (Sandbox Code Playgroud)
怎么会这样?
如果我使用相同的话
A.withCriteria {
isNotNull 'b'
}*.b
Run Code Online (Sandbox Code Playgroud)
我做错了什么?
更新:
我意识到问题是因为hasOne.如果相反的static hasOne = [b: B],还有B b,它的工作原理.前者将外键移动到表B,后者在表A中创建外键关系.那么为什么查询在前一种情况下不起作用,如何查询所有As,而不是B外键何时在内B'
感谢@Koloritnij 的评论和@Alexander Suraphel 的修改答案,我终于解决了。感谢那。
如果外键在B表上(由于hasOne),则以下两个查询解决了这种情况:
A用Bs: (b不是null)找出所有s :
A.withCriteria {
b {}
}
Run Code Online (Sandbox Code Playgroud)
这导致内部联接: SELECT * FROM a INNER JOIN b ON a.id=b.a_id;
找到没有s 的所有As ( is ): Bbnull
A.withCriteria {
createAlias('b', 'bAlias', CriteriaSpecification.LEFT_JOIN)
isNull 'bAlias.id'
}
Run Code Online (Sandbox Code Playgroud)
这导致左外连接: SELECT * FROM a LEFT OUTER JOIN b ON a.id=b.a_id WHERE b.id IS NULL;