I am new to grails - Gorm so any help would be appreciated. I have a domain object called "Employee" as following :
class Employee {
String firstName
String lastName
Set<Workplace> workplaces = new HashSet<>()
static hasMany = [workplaces: Workplace]
static mapping = {
workplaces cascade: 'all-delete-orphan'
}
}
The Employee has a one-to-many relation with a Domain called "Workplace"
class Workplace {
Employee employee
Country country
Company company
LocalDate startDate
LocalDate endDate
static belongsTo = [employee: Employee]
}
The "Country" and "Company" domains , are domain objects defined in a plugin that I have added a dependency to.I fill predefined values of company and countries in my Bootstrap.groovy.Here are the classes :
class Company {
String cmpCode
static constraints = {
cmpCode blank: false, maxSize: 255, unique: true
}
}
class Country {
String ctyCode
static constraints = {
ctyCode blank: false, maxSize: 255, unique: true
}
Country(String ctyCode) {
this.ctyCode = ctyCode
}
}
and this is how I save/update the employee (after adding all the related workplaces)
@Transactional
Employee merge(Employee employee) {
employee = employee.merge()//have tried with flush:true does not work
return employee
}
Now My problem is as following : When I add different workplaces to my employee and try to save/merge the Employee object, it works if and only if the company and country codes in my workplaces are unique. If I try to add workplaces with the same country,company but different start/end dates it throws the following exception : org.hibernate.NonUniqueObjectException: A different object with the same identifier value was already associated with the session : [Company](It can be Country also)
To me it sounds like GORM tries to save the country and companies again and as the transaction is not committed yet and the previous workplace is still in the session , hibernate throws exception. Is there any solution to this? What am I doing wrong here? any suggestions ? I'm using Grails 3.3.9
merge
service? I think that will give more clue for us to help you much. – Tung