JPA/Hibernate:复合主键、@IdClass 或 @EmbeddedId 实现哪个更好?为什么?
对于 JPA/Hibernate 复合主键,@IdClass
或 @EmbeddedId
实现哪个更好?为什么?
这是一个故意幼稚的问题。我决定使用 @EmbeddedId (无论出于何种原因),我觉得我做出了错误的选择。取消引用包含列属性的嵌入Id是多余的,并且在编码时很容易出错。
还有更多支持和/或反对对方的理由吗?这是 JPA(规范)的推荐吗?
what's better for JPA/Hibernate composite primary keys, @IdClass
or @EmbeddedId
implementations and why?
This is an intentionally naive question. I decided to use @EmbeddedId
(for whatever reason) and I feel like I made the wrong choice. Dereferencing the embeddedId that contains the column properties is redundant and quite error-prone when coding.
Are there any more reasons for and/or against the other? Is the a recommendation by the JPA (spec)?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
首先,如果可能的话,不惜一切代价避免使用复合 id。但如果您确实需要,我会推荐
@EmbeddedId
。@IdClass
基本上是 EJB 2.1 时代的遗留物,以便更容易从 BMP 迁移。在其他一些罕见的极端情况下,它也可能比@EmbeddedId
更好。然而,通常@EmbeddedId
更好,更面向对象,因为它在对象中更好地封装了键的概念。如果您需要在关键字段中使用,您可能需要使用
@AttributeOverride(s)
。我不明白你为什么认为取消引用嵌入的 id 是多余的并且容易出错。
First, if possible, avoid composite ids at all costs. But if you really need, I would recommend
@EmbeddedId
.@IdClass
is basically a leftover from EJB 2.1 times to make it easier from migrating from BMP. In some other rare corner cases it may be better than@EmbeddedId
too. However, generally@EmbeddedId
is better and more OO since it encapsulates the concept os the key much better in the object.You may want to use
@AttributeOverride(s)
if you need in the key field.I don't see why do you think that dereferencing the embedded id is redundant and error-prone.
正如帕斯卡在这里写的,这是答案的一部分:
我应该使用哪个注释:@ IdClass 或 @EmbeddedId
最后,我相信在实践中使用
@IdClass
更容易,因为您必须添加embeddedId
属性名称来取消引用 PK 属性,虽然这些并不是为所有非 PK 属性编写的。您始终必须准确记住哪些属性是 PK 的一部分,哪些不是。这使得 JPQL 查询的编写变得不必要地复杂化。
另外,据我所知,JPA 2.0 规范允许您将
@Id
放到@XToX
/@JoinColumn
/s 属性上,并引入了@MapsId
注释,以便映射标识关系(又名 JPA 中的派生标识符)更自然地实现。As Pascal wrote here's part of the answer:
Which annotation should I use: @IdClass or @EmbeddedId
In the end, I believe using
@IdClass
is much easier in practice, because you have to add theembeddedId
property name to dereference PK properties, while these aren't written for all non-PK properties.You always have to remember exactly which properties are part of a PK and those which are not. That complicates writing JPQL queries unneccessarily.
Also, AFAIK the JPA 2.0 spec allows you to put
@Id
onto@XToX
/@JoinColumn
/s properties and it introduces the@MapsId
annotation, so that mapping identifying relationships (a.k.a. derived identifiers in JPA) are more natural to implement.I. 记住使用 idclass 来做到这一点。但我建议尽一切努力避免多字段键。他们只是创造了额外的工作。
I. Remember using idclass to do it. But I'd recommend doing everything you can to avoid multi field keys. They just create extra work.