【问题标题】:Why UserRole implements Serializable and override equals() and hashcode() method为什么 UserRole 实现 Serializable 并覆盖 equals() 和 hashcode() 方法
【发布时间】:2014-03-19 07:58:42
【问题描述】:

在 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 已经复合在 User 和 Role 上?

【问题讨论】:

    标签: grails spring-security grails-orm


    【解决方案1】:

    【讨论】:

    • 我从 UserRole 中删除了 Serializable 接口和等于 hashcode 方法,并在 mysql 和 mongodb 上进行了测试。当使用 mysql 和 hibernate 时,它​​给出了“org.hibernate.MappingException:composite-id class must implement Serializable”。但是与 mongodb 完美配合。所以我认为它只在数据源处于休眠状态时才需要。如果我是正确的,应该在 spring security core 插件文档中提及,因为这个插件被各种数据源使用。
    • 顺便说一句,感谢您提供此信息。我对休眠一无所知,我对序列化知之甚少。我的脑海中仍然存在一个问题。为什么 hibernate 强加了实现 Serializable 接口的条件?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-01-22
    • 1970-01-01
    相关资源
    最近更新 更多