本文翻译自:The JPA hashCode() / equals() dilemma
There have been some discussions here about JPA entities and which hashCode()
/ equals()
implementation should be used for JPA entity classes. 这里有一些关于JPA实体的讨论 ,以及哪些hashCode()
/ equals()
实现应该用于JPA实体类。 Most (if not all) of them depend on Hibernate, but I'd like to discuss them JPA-implementation-neutrally (I am using EclipseLink, by the way). 大多数(如果不是全部)它们依赖于Hibernate,但我想讨论它们JPA实现中性(顺便说一下,我使用的是EclipseLink)。
All possible implementations are having their own advantages and disadvantages regarding: 所有可能的实现都有各自的优点和缺点 :
-
hashCode()
/equals()
contract conformity (immutability) forList
/Set
operationshashCode()
/equals()
)用于List
/Set
操作的合同一致性 (immutability) - Whether identical objects (eg from different sessions, dynamic proxies from lazily-loaded data structures) can be detected 是否可以检测到相同的对象(例如来自不同会话,来自延迟加载的数据结构的动态代理)
- Whether entities behave correctly in detached (or non-persisted) state 实体是否在分离(或非持久)状态下正常运行
As far I can see, there are three options : 据我所知,有三种选择 :
- Do not override them; 不要覆盖它们; rely on
Object.equals()
andObject.hashCode()
依赖于Object.equals()
和Object.hashCode()
-
hashCode()
/equals()
workhashCode()
/equals()
工作 - cannot identify identical objects, problems with dynamic proxies 无法识别相同的对象,动态代理的问题
- no problems with detached entities 分离实体没有问题
-
- Override them, based on the primary key 根据主键覆盖它们
-
hashCode()
/equals()
are brokenhashCode()
/equals()
被破坏了 - correct identity (for all managed entities) 正确的身份(适用于所有管理实体)
- problems with detached entities 分离实体的问题
-
- Override them, based on the Business-Id (non-primary key fields; what about foreign keys?) 根据Business-Id (非主键字段;外键怎么样?)覆盖它们。
-
hashCode()
/
-