JPA / Hibernate:对于组合主键,@IdClass或@EmbeddedId实现什么更好?为什么? [英] JPA/Hibernate: What's better for composite primary keys, @IdClass or @EmbeddedId implementations and why?

查看:186
本文介绍了JPA / Hibernate:对于组合主键,@IdClass或@EmbeddedId实现什么更好?为什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对于JPA / Hibernate组合主键,@IdClass或@EmbeddedId实现以及为什么更好?



这是一个有意无意的问题。我决定使用@EmbeddedId(出于任何原因),我觉得我做出了错误的选择。取消引用包含列属性的embeddedId是多余的,并且在编码时很容易出错。



是否还有其他原因和/或针对另一个原因?是由JPA(spec)推荐的吗?

解决方案

这是Pascal写的答案的一部分:

b
$ b

我应该使用哪个注释: @IdClass或@EmbeddedId



最后,我相信使用 @IdClass 练习,因为你必须添加 embeddedId 属性名来解引用PK属性,而这些属性并不是为所有非PK属性编写的。



你总是要记住哪些属性是PK的一部分,哪些属性不属于PK。 JPA 2.0规范的AFAIK允许你把 @Id 放到 code> @XToX / @JoinColumn / s属性,它引入了 @MapsId 注释,因此映射标识关系(也称为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)?

解决方案

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 the embeddedId 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.

这篇关于JPA / Hibernate:对于组合主键,@IdClass或@EmbeddedId实现什么更好?为什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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