JPA providers: why do relationships/FKs to non-PK

2019-07-20 05:17发布

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?

2条回答
贼婆χ
2楼-- · 2019-07-20 05:45

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.

查看更多
混吃等死
3楼-- · 2019-07-20 06:01

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.

查看更多
登录 后发表回答