在equals和hashCode中说明hasMany关系 [英] Account for hasMany relationships in equals and hashCode
本文介绍了在equals和hashCode中说明hasMany关系的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想使用 @EqualsAndHashCode 我的域类上的注释,但似乎该注释生成的equals
和hashCode
方法没有考虑hasMany
字段.我看不到有任何方法可以通过注释来更改它,但是我希望我缺少一些东西,因为它非常方便(如果可以的话).
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).
推荐答案
- 在父域类中将
hasMany
关系定义为Set
,我们通常不这样做,因为它是多余的. - 您还必须确保对子域使用
@EqualsAndHashCode
AST. - 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.
例如:
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
}
以防万一,您正在考虑索引hasMany项,然后使用List
而不是Set
.
In case, you are thinking of indexing hasMany items, then use List
instead of Set
.
这篇关于在equals和hashCode中说明hasMany关系的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文