Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should I implement equals and hashCode in a domain class?

Tags:

grails

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

It seems like this shouldn't be needed because there is always an id.

like image 445
John Mercier Avatar asked Apr 16 '15 18:04

John Mercier


1 Answers

In the Grails Book "Programming Grails" Burt says about equals & hashCode (and i hope i'm getting it right here), that they should be implemented in scenarios of proxy usage (like when doing lazy-loading or Customer.load()) and be stored in a collection. Because if a proxy entity as well as an un-proxied entity are stored within a collection, they are not treated as the "same" object.

As Hibernate normally uses un-proxied versions of a domain instance if it is already in the first-level cache (the Hibernate session), this problem only occurs if you have an domain object, that is not in the current hibernate session (like the http session).

If you want to avoid that much boilerplate code, you can use the Annotation @EqualsAndHashCode (see docs) like the following:

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

For more information see "Programming Grails - Burt Beckwith" First Edition, page 134.

like image 80
Mario David Avatar answered Oct 18 '22 21:10

Mario David