Best practice regarding the inclusion of id of domain model on equals implementation

走远了吗. 提交于 2019-12-24 15:21:41

问题


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

  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


来源:https://stackoverflow.com/questions/29207268/best-practice-regarding-the-inclusion-of-id-of-domain-model-on-equals-implementa

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!