What is the best practice regarding implementation of equals of domain model in grails?
Do we include the id field or just the business rule relevant fields?Answer1:
Hibernate suggests that you include just the business key / candidate key in the equals implementation. Including the id field in the equals implementation can have negative consequences if you have generated id field. Hibernate assigns id only when saving the object (if you are using generated ids). Now for example, if your new unsaved domain object is in a HashSet and you save the domain, it will generate and assign the id to the domain, the hashcode of the domain will change if your equals / hashcode is based on id field, and your domain will be lost in set.
It is suggested that you implement equals using unique immutable fields.
See references<ol><li><a href="https://docs.jboss.org/hibernate/stable/core.old/reference/en/html/persistent-classes-equalshashcode.html" rel="nofollow">https://docs.jboss.org/hibernate/stable/core.old/reference/en/html/persistent-classes-equalshashcode.html</a></li> <li><a href="http://www.onjava.com/pub/a/onjava/2006/09/13/dont-let-hibernate-steal-your-identity.html" rel="nofollow">http://www.onjava.com/pub/a/onjava/2006/09/13/dont-let-hibernate-steal-your-identity.html</a></li> <li><a href="https://stackoverflow.com/questions/1638723/equals-and-hashcode-in-hibernate" rel="nofollow">Similar question</a></li> </ol>