[英]Grails GORM query for null hasOne association fails
我使用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]
}
我嘗試查找具有B的A的所有實例。
A.findAllByBIsNotNull()*.b
返回B和null的列表:
[null, null, b1, b2, null, ...]
為何如此?
如果我使用同樣的情況
A.withCriteria {
isNotNull 'b'
}*.b
我做錯了什么?
更新:
我意識到問題是因為hasOne
。 如果不是static hasOne = [b: B]
,則有B b
,它可以工作。 前者將外鍵移到表B,后者在表A中創建外鍵關系。那么為什么查詢在前一種情況下不起作用,以及如何查詢所有A
,而外鍵時沒有B
在B內嗎?
由於@Koloritnij的評論和@Alexander Suraphel的修改后的答案,我終於解決了它。 感謝那。
如果外鍵在B
表上(由於hasOne
),則以下兩個查詢解決了這種情況:
查找所有具有B
的A
:( b
不為null
):
A.withCriteria {
b {}
}
這將導致內部SELECT * FROM a INNER JOIN b ON a.id=b.a_id;
: SELECT * FROM a INNER JOIN b ON a.id=b.a_id;
查找所有不帶 B
的A
( b
為null
):
A.withCriteria {
createAlias('b', 'bAlias', CriteriaSpecification.LEFT_JOIN)
isNull 'bAlias.id'
}
這將導致左外部連接: SELECT * FROM a LEFT OUTER JOIN b ON a.id=b.a_id WHERE b.id IS NULL;
以下更新:
使用B
中的字段之一。 假設B
具有字段name
:
A.withCriteria { b { isNotNull("name") }}*.b
舊答案:
問題可能出在B類的toString()
中。
加
String toString() {
getClass().name
}
B
類,然后嘗試再次運行查詢。
如果您只需要拿B,為什么不能使用:
B.findAll()
或如果通過A:
B.findAllByA(a)
UPD:使用條件:
A.createCriteria().list{
isNotNull 'B'
isNull 'C'
}
或這不是一個好主意,但必須起作用:
def bList = B.createCriteria().list{
projections{
property 'id'
}
A.createCriteria().list{
b{
'in' ('id',bList)
}
}
那不是A.findAllBybIsNotNull()*.b
(注意小寫b)嗎?
要么
A.findAll("from A as a where ab is null")
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.