Grails:复杂的多对多GORM查询

时间:2012-12-08 12:19:14

标签: hibernate grails hql gorm

我有5张桌子:

User (Mark)
Enterprise (Google)
EnterpriseUser (Mark,  Google)
EnterpriseRight (LOGIN)
EnterpriseUserRight (Mark-Google, LOGIN)

我想使用GORM查询Mark(当前用户)拥有LOGIN权限的所有企业的数据库。然后,我希望能够对结果进行排序和分页。

我之前通过构建List来做到这一点,但我会引用返回ResultSet(仍然可以对其进行排序/分页/查询)

我的User.class(域对象)尝试(生成列表< Enterprise>)

public List<Enterprise>getEnterprises() {
    def list = new ArrayList<Enterprise>()
    for (EnterpriseUser eu: this.enterpriseUsers) {
        if (this.hasEnterpriseRights(eu.enterprise, [EnterpriseRight.LOGIN])) {
            list.add(eu.enterprise)
        }
    }
    return list
}

(但是我无法对这些结果进行排序和分页,因为它们现在是一个列表。如果此查询可以返回结果集,那就太好了)

英文:

查找与此Enterprise相关联的所有User,此用户的EnterpriseRight字符串名称为“LOGIN”。按字母顺序列出,从Offset 10给我10个结果。

我会在这里发布我的代码,但我不知道从哪里开始。

域对象是:

class User {

    static hasMany = [userSystemRights: UserSystemRight, enterpriseUsers: EnterpriseUser]

    String email;   
    String passwordHash;
}    

class Enterprise {

    static hasMany = [enterpriseUsers: EnterpriseUser, measurements: Measurement]

    String name = ""
    String tradingName = ""
}

class EnterpriseUser {

    static belongsTo = [enterprise: Enterprise, user: User]
    static hasMany = [enterpriseUserRights: EnterpriseUserRight]

    Enterprise enterprise
    User user
    String interest
}

class EnterpriseUserRight {

    static belongsTo = [enterpriseUser: EnterpriseUser, enterpriseRight: EnterpriseRight]

    EnterpriseUser enterpriseUser
    EnterpriseRight enterpriseRight

}

class EnterpriseRight {

    public static final String LOGIN = "LOGIN"
    public static final String MANAGE_USERS = "MANAGE_USERS"
    public static final String MANAGE_SETTINGS = "MANAGE_SETTINGS"

    static hasMany = [enterpriseUserRights: EnterpriseUserRight]    

    String name
}

1 个答案:

答案 0 :(得分:2)

我不知道Grails是否也有一个特殊的DSL用于查询,但在HQL中,你会这样做:

select distinct enterprise from EnterpriseUserRight enterpriseUserRight
inner join enterpriseUserRight.enterpriseRight enterpriseRight
inner join enterpriseUserRight.enterpriseUser enterpriseUser
inner join enterpriseUser.enterprise enterprise
where enterpriseRight.name = 'LOGIN'
and enterpriseUser.user = :user
order by enterprise.name