Grails:带有可选关联的"where"查询

Har*_*cle 3 sql grails hibernate where

我正在尝试运行"where"查询以查找与另一个域模型对象没有关联的域模型对象,或者如果是,则该域模型对象具有特定的属性值.这是我的代码:

query = Model.where({
  other == null || other.something == value
})
def list = query.list()
Run Code Online (Sandbox Code Playgroud)

但是,结果列表仅包含与OR语句的第二部分匹配的对象.它不包含与"other == null"部分匹配的结果.我的猜测是,因为它正在检查关联对象中的值,所以它强制它仅检查实际具有此关联对象的条目.如果是这种情况,我该如何创建此查询并实际使其正常工作?

dma*_*tro 5

您必须使用LEFT JOIN才能查找空关联.默认情况下,Grails使用内部联接,不会为null结果加入.使用withCriteria如下所示,您应该得到预期的结果:

import org.hibernate.criterion.CriteriaSpecification

def results = Model.withCriteria {
    other(CriteriaSpecification.LEFT_JOIN){
        or{
            isNull 'id'
            eq 'something', value
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

更新
我知道在DetachedCritieria中不能使用别名,其中一个人会尝试将连接指定为createCriteria/withCriteria.有关向DetachedCriteria添加功能现有缺陷.只是为缺陷中提到的查询添加工作.

Model.where {
    other {
        id == null || something == value
    }
}.withPopulatedQuery(null, null){ query -> 
    query.@criteria.subcriteriaList[0].joinType = CriteriaSpecification.LEFT_JOIN
    query.list()
}
Run Code Online (Sandbox Code Playgroud)

我宁愿使用withCriteria而不是上面的黑客.