JPA/休眠键和复合键 [英] JPA/Hibernate and composite keys

查看:105
本文介绍了JPA/休眠键和复合键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到了一些 SO 讨论和其他帖子(例如这里这里),其中在 JPA 中使用复合主键被描述为在可能的情况下应避免的情况,或者由于遗留数据库或具有毛发"的极端情况而被认为是必需的.由于我们是从头开始设计新的数据库,因此建议还是说没有任何遗留问题可以考虑,或更安全,以避免使用 JPA (休眠 strong>或 EclipseLink ?).

I have come across some SO discussions and others posts (e.g. here, here and here) where using composite primary keys with JPA is described either as something to be avoided if possible, or as a necessity due to legacy databases or as having "hairy" corner cases. Since we are designing a new database from scratch and don't have any legacy issues to consider is it recommended or let's say, safer, to avoid composite primary keys with JPA (either Hibernate or EclipseLink?).

我自己的感觉是,由于 JPA 引擎足够复杂,并且当然,像所有软件一样,并非没有错误,与遭受标准化攻击的恐怖相比,遭受非规范化表的攻击可能是最好的选择与组合主键有关的错误(理由是数字单列主键和外键是JPA引擎支持的最简单的用例,因此应尽可能没有错误).

My own feeling is that since JPA engines are complex enough and certainly, like all software, not without bugs, it may be best to suffer non-normalized tables than to endure the horror of running against a bug related to composite primary keys (the rationale being that numeric single-column primary keys and foreign keys are the simplest use case for JPA engines to support and so it should be as bug-free as possible).

推荐答案

我已经尝试了这两种方法,并且由于某些原因,我个人更喜欢避免使用复合主键:

I've tried both methods, and personally I prefer avoiding composite primary keys for several reasons:

  • 您可以创建一个包含id字段的超类,因此您不必在所有实体中都麻烦它.
  • 创建实体变得容易得多
  • JPA总体上表现更好
  • 引用实体变得更加容易.例如,只需要使用一个数字就可以大大简化在一个集合中存储一堆ID或在网页的查询字符串中指定单个ID的过程.
  • 您可以使用在超类中指定的单个equals方法,该方法适用于所有实体.
  • 如果您使用JSF,则可以创建一个通用转换器
  • 使用数据库客户端时更容易指定对象

但是它也会带来一些不好的地方:

But it brings some bad parts aswell:

  • 少量非正规化
  • 使用非持久对象(如果应该使用自动生成的ID,应该使用它)在某些情况下可能会带来麻烦,因为相等方法和此类方法需要ID才能正常工作

这篇关于JPA/休眠键和复合键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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