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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With