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

时间:2011-04-28 12:10:12

标签: hibernate jpa mapping

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

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

是否允许这种常见情况?

2 个答案:

答案 0 :(得分:9)

@axtavt:好像你的答案不正确。我刚收到一封来自“Pro JPA 2.0”作者的电子邮件,他们也在研究JPA规范。

“在您的示例中,Zip类与国家/地区有关系:

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规范根本不允许关系/ FK到非PK列......

答案 1 :(得分:7)

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

但是,只要您没有派生身份(即,如果您可以手动设置主键组件的值),您可以尝试使用只读映射,如下所示:

@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

    ...
}
相关问题