JPA 提供者:为什么与非 PK 列的关系/FK 在 Hibernate 和 EclipseLink 中有效?

发布于 2024-11-04 08:11:27 字数 334 浏览 1 评论 0原文

我刚刚发现 JPA 不支持非主键列的正式关系/外键。请参阅此处:

JPA 规范是否允许对非主键列的引用?

为什么这样的关系在 Hibernate 和 EclipseLink 中映射(仅在 JPA 1.0 语法中,如发布的示例中所示)?

看来这些 JPA 提供者只是天真地映射列,我认为这是一件好事,但我想明确地知道。是巧合吗?是故意的吗?

I just found out that officially relationships/foreign keys to non-primary key columns aren't supported by JPA. See here:

Does the JPA specification allow references to non-primary key columns?

Why do such relationships map in Hibernate and EclipseLink nontheless (only in JPA 1.0 syntax as in the example posted there)??

It appears that these JPA providers just map the columns naively, which I think is a good thing, but I'd like to know explicitly. Is it coincidence? Is it intended?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

心碎无痕… 2024-11-11 08:11:27

支持引用非 PK 列的 FK 是一个可选功能(而且总是如此,因此没有“JPA 1.0 语法”,我之前的答案是不正确的):

对不是引用表主键列的引用列的支持是可选的。
使用此类映射的应用程序将不可移植。

但是,Hibernate 支持它:

它还有一个名为referencedColumnName 的参数。此参数声明目标实体中将用于连接的列。请注意,当对非主键列使用referencedColumnName 时,关联的类必须是可序列化的。另请注意,非主键列的referencedColumnName 必须映射到具有单个列的属性(其他情况可能不起作用)。

不过,正如已经发现的那样,这种关系不能用作派生身份的一部分。

Support of FK that references non-PK columns is an optional feature (and it always was so, thus there is no "JPA 1.0 syntax", my previous answer was incorrect):

Support for referenced columns that are not primary key columns of the referenced table is optional.
Applications that use such mappings will not be portable.

However, Hibernate supports it:

It has one more parameters named referencedColumnName. This parameter declares the column in the targeted entity that will be used to the join. Note that when using referencedColumnName to a non primary key column, the associated class has to be Serializable. Also note that the referencedColumnName to a non primary key column has to be mapped to a property having a single column (other cases might not work).

Though, as it have been found out already, such a relationship can't be used as a part of dervied identity.

つ低調成傷 2024-11-11 08:11:27

EclipseLink/TopLink 始终允许外键有意指向任何表字段,因为对象的主键不一定需要是表上使用的 pks - 任何唯一标识符都可以。

只是猜测,但使用主键可能是 JPA 规范确保强制执行唯一标识符的一种方法,并且不使用 pk 还会产生其他性能影响,因为缓存/对象标识通常仅使用主键来完成- 所以这可能会导致额外的数据库命中。

EclipseLink/TopLink has always allowed foreign keys to point to any table field intentionally, as an object's primary keys didn't neccessarily need to be the pks used on the table - any unique identifier would do.

Just a guess, but using the primary key might have been one way for the JPA spec to ensure that a unique identifier is enforced, and not using the pk also has other performance implications as caching/object identity is usually only done using the primary key - so it might result in extra database hits.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文