JPA hashCode()/ equals()两难

本文翻译自: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) for List / Set operations hashCode() / 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 : 据我所知,有三种选择

  1. Do not override them; 不要覆盖它们; rely on Object.equals() and Object.hashCode() 依赖于Object.equals()Object.hashCode()
    • hashCode() / equals() work hashCode() / equals()工作
    • cannot identify identical objects, problems with dynamic proxies 无法识别相同的对象,动态代理的问题
    • no problems with detached entities 分离实体没有问题
  2. Override them, based on the primary key 根据主键覆盖它们
    • hashCode() / equals() are broken hashCode() / equals()被破坏了
    • correct identity (for all managed entities) 正确的身份(适用于所有管理实体)
    • problems with detached entities 分离实体的问题
  3. Override them, based on the Business-Id (non-primary key fields; what about foreign keys?) 根据Business-Id (非主键字段;外键怎么样?)覆盖它们。
    • hashCode() /
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值