有关在等同执行中包含域模型id的最佳实践 [英] Best practice regarding the inclusion of id of domain model on equals implementation

查看:103
本文介绍了有关在等同执行中包含域模型id的最佳实践的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



我们是否包含id字段或仅包含业务规则相关字段?

解决方案

Hibernate建议您在equals实现中只包含业务密钥/候选键。如果您已经生成了id字段,那么在等号实现中包含id字段可能会产生负面后果。 Hibernate只在保存对象时才分配id(如果使用生成的id)。现在例如,如果您的新未保存的域对象位于HashSet中并且您保存了域,它将生成并将该ID分配给该域,如果您的equals / hashcode基于id域,则该域的哈希码将会更改,并且您的域名将会丢失。



建议您使用唯一的不可变字段实现等于。



请参阅参考资料


  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. 类似的问题


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?

解决方案

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

这篇关于有关在等同执行中包含域模型id的最佳实践的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆