在Grails中,Spring安全核心插件有助于创建用户和角色域。由于其中有多对多关系,因此创建了第三个域UserRole。
UserRole.groovy
import org.apache.commons.lang.builder.HashCodeBuilder
class UserRole implements Serializable {
private static final long serialVersionUID = 1
User user
Role role
boolean equals(other) {
if (!(other instanceof UserRole)) {
return false
}
other.user?.id == user?.id &&
other.role?.id == role?.id
}
int hashCode() {
def builder = new HashCodeBuilder()
if (user) builder.append(user.id)
if (role) builder.append(role.id)
builder.toHashCode()
}
static UserRole get(long userId, long roleId) {
UserRole.where {
user == User.load(userId) &&
role == Role.load(roleId)
}.get()
}
static UserRole create(User user, Role role, boolean flush = false) {
new UserRole(user: user, role: role).save(flush: flush, insert: true)
}
static boolean remove(User u, Role r, boolean flush = false) {
int rowCount = UserRole.where {
user == User.load(u.id) &&
role == Role.load(r.id)
}.deleteAll()
rowCount > 0
}
static void removeAll(User u) {
UserRole.where {
user == User.load(u.id)
}.deleteAll()
}
static void removeAll(Role r) {
UserRole.where {
role == Role.load(r.id)
}.deleteAll()
}
static mapping = {
id composite: ['role', 'user']
version false
}
}
我从未见过或创建过实现Serializable接口的域类。我认为grails在内部处理序列化过程。那么为什么UserRole实现了Serializable?这里覆盖equals()和hascode()方法的优势是什么,因为UserRole的id已经在用户和角色上复合了?
答案 0 :(得分:1)