gpt4 book ai didi

java - Grails:GORM:遍历多对多关系

转载 作者:行者123 更新时间:2023-12-02 00:07:18 26 4
gpt4 key购买 nike

我有 2 个域对象,User 和 SystemRights(这是多对多,因此 1 个用户可以拥有多个权限,1 个权限可以由多个用户拥有)。我正在寻找一种简单的方法来检查用户是否拥有所需的权限。

用户域

class User {

static hasMany = [systemRights: SystemRight, enterpriseUsers: EnterpriseUser]

String email;
String passwordHash;
}

系统权限域

class SystemRight {

public static final String LOGIN = "LOGIN"
public static final String MODIFY_ALL_ENTERPRISES = "MODIFY_ALL_ENTERPRISES"
public static final String ADMINISTER_SYSTEM = "ADMINISTER_SYSTEM"
public static final String VALIDATE_SUPPLIER_SCORECARDS = "VALIDATE_SUPPLIER_SCORECARDS"

static hasMany = [users:User]
static belongsTo = User

String name
}

以下内容对我不起作用:

在 User.class 中

public boolean hasRights(List<String> requiredRights) {

def userHasRight = SystemRight.findByUserAndSystemRight (this, SystemRight.findByName(requiredRight));

// Nor this

def userHasRight = this.systemRights.contains(SystemRight.findByName(requiredRight));

}

当前糟糕的解决方案

public boolean hasRights(List<String> requiredRights) {

for (String requiredRight : requiredRights) {

def has = false

for (SystemRight userRight : user.systemRights) {
if (userRight.name == requiredRight) {
has = true
break;
}
}

if (has == false) {
return false;
}
}

return true

}

最佳答案

如果您能够/愿意稍微改变一下,我强烈建议您执行以下操作。它将使您的生活变得更加轻松。

首先,从两个域中删除 SystemRight 和 User 的 hasMany,并从 SystemRight 中删除belongsTo User。

接下来,创建域来表示连接表。

class UserSystemRight {
User user
SystemRight systemRight

boolean equals(other) {
if (!(other instanceof UserSystemRight)) {
return false
}
other.user?.id == user?.id && other.systemRight?.id == systemRight?.id
}

int hashCode() {
def builder = new HashCodeBuilder()
if (user) builder.append(user.id)
if (systemRight) builder.append(systemRight.id)
builder.toHashCode()
}


// add some more convenience methods here if you want like...
static UserSystemRight get(long userId, long systemRightId, String systemRightName) {
find 'from UserSystemRight where user.id=:userId and systemRight.id=:systemRightId and systemRight.name=:systemRightName',
[userId: userId, systemRightId: systemRightId, systemRightName: systemRightName]
}
}

然后,在您的 User 类中,您可以添加此方法:

Set<SystemRight> getSystemRights() {
UserSystemRight.findAllByUser(this).collect { it.systemRight } as Set
}

然后,将其添加到您的 SystemRight 域:

Set<User> getUsers() {
UserSystemRight.findAllBySystemRight(this).collect { it.user } as Set
}

要更详细地解释为什么这种方法除了实际解决您的问题之外还充满胜利,take a gander at this .

关于java - Grails:GORM:遍历多对多关系,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13572912/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com