grails - grails,hasMany,set和重复项

标签 grails gorm

grails文档说默认情况下hasMany是一个集合。
我的域如下所示:

class Employee {
    String name;
    String empId;
    String password;
    String contactNumber;
    String emailId;

    static hasMany = [roles : Role]

    static belongsTo = [department : Department]

    static constraints = {
        contactNumber nullable : true
        emailId nullable : true
        empId unique : true
        roles nullable : true
        department nullable : true
    }

    static mapping = {
        sort name : "asc"
    }
}

//Role class
class Role {
    String role;
    String roleId;
}

Controller 中的以下代码允许向“角色”添加重复的条目:
roleListToBeAdded.each { r ->
                        println "Trying to add ${r}"
                        try {
                            employee.addToRoles(r).save(flush:true)
                        } catch (Exception e) {
                            println "failed to add ${r}: ${e}"
                        }
                    }

为什么会这样呢?

注意:如果 roleListToBeAdded 具有多个相同角色的条目(例如,如果请求JSON看起来像这样:{“rolesToBeAdded”:[{“role”:33},{“role”:33}}),那么它没有添加两次,但是如果说已经添加了角色33,并且我再次使用role:33发出了一个新请求,那么它将在'employee_role'表中再添加一条记录。

最佳答案

您需要向Role类添加适当的equalshashCode,因为“设置唯一性”基于Java相等性而不是数据库身份。等于定义应基于数据(例如角色名称)而不是数据库ID,因为“临时”实例(尚未保存的实例)具有空ID。

关于grails - grails,hasMany,set和重复项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21523376/

相关文章:

grails - 房子属于主人?

grails - 在 grails 中记录

hibernate - Grails的hasOne和hasMany具有相同的域和级联操作

grails - CountBy WithCriteria不匹配

grails - Grails中的动态MongoDb查询

grails - Grails发布关联列表中的重复姓氏

grails - 如何将数据从一个grails应用程序发送到另一grails应用程序

grails run-app 随机抛出 : java. lang.NoClassDefFoundError: Lorg/codehaus/groovy/grails/plugins/web/async/api/ControllersAsyncApi

mongodb - 如何使用Grails 2.2.2从mongoDb检索数据

grails - GORM继承