Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
367 views
in Technique[技术] by (71.8m points)

grails - Account for hasMany relationships in equals and hashCode

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).

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
  • 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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...