I would like to use the @EqualsAndHashCode annotation on my domain classes, but it seems the equals
and hashCode
methods generated by that annotation don't take hasMany
fields into account. I don't see any way to change this with the annotation, but I'm hoping that I'm missing something because it is very convenient (if it works).
可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
回答1:
- Define the
hasMany
relationship as aSet
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
.