The grails document says that by default hasMany is a set. My domain looks like this:
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;
}
And the following code in the controller allows to add duplicate entries to 'roles':
roleListToBeAdded.each { r ->
println "Trying to add ${r}"
try {
employee.addToRoles(r).save(flush:true)
} catch (Exception e) {
println "failed to add ${r}: ${e}"
}
}
why is this so ?
Note: If roleListToBeAdded has multiple entries of same role (For, example: if the request JSON looks like this : {"rolesToBeAdded" : [{"role":33}, {"role":33}}) then it is not adding two times, but if say role 33 is already added and I make a new request one more time with role:33, then it adds one more record in 'employee_role' table.
You need to add an appropriate equals
and hashCode
to the Role class as Set uniqueness is based on Java equality rather than database identity. The equals definition should be based on the data (e.g. the role name) rather than the database ID, as "transient" instances (those that have not yet been saved) have null ids.