【发布时间】:2014-02-03 18:30:06
【问题描述】:
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;
}
控制器中的以下代码允许将重复条目添加到“角色”:
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 已经添加并且我使用角色:33 再次发出新请求,那么它会在 'employee_role' 表中添加一条记录。
【问题讨论】:
-
Role类是什么样的,尤其是它的equals和hashCode实现? -
我已经编辑了帖子并包含了 Role 类。
标签: grails grails-orm