Grails 2.x createCriteria 'or' 不适用于嵌套关联 [英] Grails 2.x createCriteria 'or' doesn't work for nested associations

查看:18
本文介绍了Grails 2.x createCriteria 'or' 不适用于嵌套关联的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

似乎在 Grails 2.x 中,如果您有域类关联,并且您尝试在该关系上使用 or 运行 createCriteria + 另一个查询,or 将忽略其他查询并仅使用嵌套关联的结果.我意识到这可能有点令人困惑,所以这里有一个例子:

It seems that in Grails 2.x, if you have a domain class association, and you try to run a createCriteria using or on that relation + another query, the or will ignore the other query and just use the results of the nested association. I realize this may be a little confusing, so here is an example:

class Passenger {
    Long id
    Boolean isDriving
}

class Car {
    Long id
    Passenger passenger
    Boolean isMoving

    static constraints = {
        passenger nullable: true
    }
}

和测试:

class CarIntegrationTests {
    @Test
    void testCar() {
    Passenger passenger1 = new Passenger(isDriving: true)
    passenger1.save()

    Car car1 = new Car(passenger: passenger1, isMoving: false)
    Car car2 = new Car(isMoving: true)

    car1.save()
    car2.save()

        def queryResults = Car.createCriteria().list() {
            or {
                eq('isMoving', true)// This by itself works

                passenger {// And this by itself works
                    eq('isDriving', true)
                }
            }// But OR'd, it only returns the results of the nested part
        }

        assertEquals 2, queryResults.size() // Returns 1
    }
}

同样的代码在旧版本的 Grails 中工作,但现在似乎不起作用——除了运行多个查询之外,有没有人知道一个好的解决方法?

This same code worked in older versions of Grails, but doesn't not seem to work now -- does anyone know of a good workaround to this, other than running multiple queries?

推荐答案

更新:
在 Grails 2.x 之后,Criteria 默认使用 inner join,但对于这种特殊情况,必须使用 outer join 作为乘客关联将不允许跟随 条件,如果它是 inner 加入并且乘客未设置为汽车.

UPDATE:
Post Grails 2.x, Criteria by default uses inner join, but for this particular case outer join has to be used as passenger association will not allow to follow or condition if it is an inner join and passenger is not set to car.

import org.hibernate.Criteria

def queryResults = Car.createCriteria().list() {
    createAlias('passenger', 'passenger', Criteria.LEFT_JOIN)
    or {
        eq('isMoving', true)
        eq('passenger.isDriving', true)
    }
}

这篇关于Grails 2.x createCriteria 'or' 不适用于嵌套关联的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆