我有 5 张 table :
User (Mark)
Enterprise (Google)
EnterpriseUser (Mark, Google)
EnterpriseRight (LOGIN)
EnterpriseUserRight (Mark-Google, LOGIN)
我想使用 GORM 来查询 Mark(当前用户)拥有 LOGIN 权限的所有企业的数据库。然后,我希望能够对结果进行排序和分页。
我以前通过构建一个列表来做到这一点,但我会提到返回一个 ResultSet(仍然可以排序/分页/查询)
我的 User.class(域对象)尝试(生成 List
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”。按字母顺序列出,从偏移量 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
}
最佳答案
我不知道 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
关于hibernate - Grails:复杂的多对多 GORM 查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13777401/