2011-04-28 119 views
18

JPA规范是否允许简单引用非主键列?JPA规范是否允许引用非主键列?

我在我想要在引用中使用的国家/地区表上有一个简单的替代/自然键(UNIQUE,NOT NULL)列iso_code,但Eclipse的Dali显示验证错误,并且Hibernate抛出了MappingException。

这样的常见情况是否允许?

回答

8

@axtavt:看起来好像你的回答不正确。我刚刚收到了来自“Pro JPA 2.0”作者的电子邮件,他们也正在从事JPA规范。

“在你的例子中,邮编类有一个国家的关系:

public class Zip implements Serializable 
{ 
    @Id 
    @Column(name = "code") 
    private String code; 

    @Id 
    @ManyToOne 
    @JoinColumn(name = "country_code", referencedColumnName = "iso_code") 
    private Country country = null; 
    ... 
} 

这似乎是试图将COUNTRY_CODE外键列指向Country表的iso_code列,这是不是一个PK。JPA从未允许您创建类似这样的关系,因为如果没有指定国家/地区的PK ,就没有办法唯一标识哪个国家/地区实例处于关系中。您只是在遇到问题时触及问题派生的标识符部分,但问题看起来是在无效关系本身。“

所以JPA规范不允许关系/ FKS非PK列在所有...

+0

请参阅http://stackoverflow.com/a/16993352/418439和http://stackoverflow.com/a/13899787/418439。所以允许还是不允许? – 2016-08-10 06:11:51

7

支持引用非PK列的关系是可选功能。在简单的情况下,它受到Hibernate的支持,但它不能被用作恶意身份的一部分。

但是,只要你没有获得一个身份(也就是说,如果你可以手动设置主键组成部分的值),你可以尝试用只读的映射,像这样玩:

@Entity 
@Table(name = "Zips") 
@IdClass(value = ZipId.class) 
public class Zip implements Serializable 
{ 
    @Id 
    @Column(name = "code") 
    private String code; 

    @Id 
    @Column(name = "country_code") 
    private String countryCode; // Primary key component should be set manually 

    @ManyToOne 
    @JoinColumn(name = "country_code", referencedColumnName = "iso_code", 
     insertable = false, updateable = false) 
    private Country country = null; // Read-only relationship based on a value 
            // of primary key component 

    ... 
} 
+0

请看看这里的具体例子+代码:http://stackoverflow.com/questions/5784272/为什么这个jpa-2-0-mapping-giving-me-an-error-in-eclipse-jboss-tools Eclipse Dali显示一个错误,Hibernate产生一个MappingException。我现在必须尝试EclipseLink。 – Kawu 2011-04-28 12:19:27

+0

我在这里创建了一个新问题:http://stackoverflow.com/questions/5818663/hibernate-bug-when-mapping-a-reference-to-an-alternative-natural-key-column-of-a – Kawu 2011-04-28 12:35:47

+0

@ Kawu:已更新。 – axtavt 2011-04-28 12:52:02