问题
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?
回答1:
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
- https://docs.jboss.org/hibernate/stable/core.old/reference/en/html/persistent-classes-equalshashcode.html
- http://www.onjava.com/pub/a/onjava/2006/09/13/dont-let-hibernate-steal-your-identity.html
- Similar question
来源:https://stackoverflow.com/questions/29207268/best-practice-regarding-the-inclusion-of-id-of-domain-model-on-equals-implementa