且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

JPA:没有覆盖实体中的equals()和hashCode()?

更新时间:2023-02-05 21:53:51

阅读这篇非常好的文章关于这个问题:不要让Hibernate窃取你的身份

Read this very nice article on the subject: Don't Let Hibernate Steal Your Identity.

文章的结论是这样的:



对象持久保存到数据库时,对象标识很难正确实现。但是,问题源于
,完全是因为在
保存之前允许对象存在而没有id。我们可以通过承担
从对象关系映射框架
(如Hibernate)中分配对象ID来解决这些问题。相反,只要实例化
对象,就可以分配对象ID。这使对象标识简单并且
无错误,并减少了域模型中所需的代码量。

Object identity is deceptively hard to implement correctly when objects are persisted to a database. However, the problems stem entirely from allowing objects to exist without an id before they are saved. We can solve these problems by taking the responsibility of assigning object IDs away from object-relational mapping frameworks such as Hibernate. Instead, object IDs can be assigned as soon as the object is instantiated. This makes object identity simple and error-free, and reduces the amount of code needed in the domain model.