- Define the
hasMany
relationship as a Set
in the parent domain class, which we normally do not do as it is redundant.
- You also have to make sure you are using
@EqualsAndHashCode
AST for the child domain.
For example:
import groovy.transform.EqualsAndHashCode
@EqualsAndHashCode
class Parent {
String name
Integer age
//Adding this as a property makes it a candidate for equals() and hashCode()
Set<Child> children
static hasMany = [children: Child]
}
@EqualsAndHashCode
class Child {
String name
static belongsTo = [parent : Parent]
}
//Unit Test
void testSomething() {
def parent1 = new Parent(name: 'Test', age: 20).save()
def child1 = new Child(name: 'Child1')
parent1.addToChildren(child1)
parent1.save()
def parent2 = new Parent(name: 'Test', age: 20).save()
def child2 = new Child(name: 'Child1')
parent2.addToChildren(child2)
parent2.save(flush: true)
assert parent1 == parent2
assert child1 == child2
}
In case, you are thinking of indexing hasMany items, then use List
instead of Set
.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…