用于左连接的GORM或HSQL独占

时间:2017-10-27 10:39:08

标签: grails

我有课程领域, 课程有一位老师或null 我想找到所有没有老师或老师的课程.id!=:loginId

如何使用GORM动态find *方法编写查询 或者使用HSQL编写它 - 我的教师属性是用户域

感谢您的帮助

1 个答案:

答案 0 :(得分:0)

hasOne Class Structure

class Course {
    User teacher

    static hasOne = [
        teacher: User
    ]
}

class User {
    // implicit id field
}

使用HQL

def getCourses(def loginId) {
    return Course.executeQuery("""
        SELECT
            c
        FROM 
            Course c
            LEFT OUTER JOIN c.teacher as t
        WHERE
            (t.id = NULL OR t.id != :logIn)
    """, [loginId: loginId])
}

使用CriteriaBuilder

import org.hibernate.criterion.CriteriaSpecification

def getCourses(def loginId) {
    return Course.createCriteria().list{
        createAlias(
            "teacher", 
            "t", 
            CriteriaSpecification.LEFT_JOIN
        )

        or {
            ne("t.id", loginId)
            isNull('t.id')
        } 
    }
}

我已经离开了过去的经历,所以我还没有测试过您的具体情况,但我相信这两种选择都应该有效。我认为,由于您需要嵌套条件(course.teacher.id != loginId),Grails动态查找器在这种情况下不起作用。