1

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?

froi
  • 7,268
  • 5
  • 40
  • 78
  • depends on your domain. are two otherwise identical objects with different ids (from your db) identical or not? – cfrick Mar 23 '15 at 10:09
  • some are identical without the ids some are not. But is it not we should apply one approach on all of them for consistency? – froi Mar 23 '15 at 11:21
  • so you rather have a common approach, that is *plain wrong half of the time*, than do the right thing™? there is no right or wrong from a consistency view, just right or wrong from your domain point of view. – cfrick Mar 23 '15 at 11:48

1 Answers1

4

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

  1. https://docs.jboss.org/hibernate/stable/core.old/reference/en/html/persistent-classes-equalshashcode.html
  2. http://www.onjava.com/pub/a/onjava/2006/09/13/dont-let-hibernate-steal-your-identity.html
  3. Similar question
Community
  • 1
  • 1
Sudhir N
  • 4,008
  • 1
  • 22
  • 32