Should I implement equals and hashCode in a domain class?

Should all Grails domain classes implement equals() and hashCode() ? Is there a default provided by Grails?

It does not seem to be necessary because there is always an id.

+6
source share
2 answers

In Grails's book β€œGrails Programming,” Bert talks about equals and hashCode (and I hope I get it here) that they should be implemented in proxy scripts (for example, with lazy loading or Customer.load() ) and stored in collection. Since, if the proxy object, as well as the non-proxied object are stored in the collection, they are not considered as the "same" object.

Since Hibernate typically uses non-proxied versions of a domain instance if it is already in the first level cache (Hibernate session), this problem only occurs if you have a domain object that is not in the current sleep mode (for example, an http session )

If you want to avoid big template code, you can use the @EqualsAndHashCode annotation (see docs ) as follows:

 @EqualsAndHashCode(includes='firstName,lastName') class Customer { String customerId String firstName String lastName } 

See "Grails Programming - Burt Beckwith" First Edition, page 134 for more information.

+16
source

By default they do not have them. You can create it using an identifier combined with some unique, not null, field. I asked to combine another field, as in some scenario (I don’t remember now). I ran into an identifier issue as the identifier was missing for this entry before insertion.

-1
source

Source: https://habr.com/ru/post/985297/


All Articles