问题
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?
回答1:
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.
回答2:
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.
来源:https://stackoverflow.com/questions/5855637/jpa-providers-why-do-relationships-fks-to-non-pk-columns-work-in-hibernate-and