OneToOne双向映射中的唯一约束

时间:2014-05-26 12:13:55

标签: java hibernate jpa hibernate-mapping one-to-one

在关系所有者的双向一对一映射中是否需要unique=true

@Entity
public class Customer {

    @Id
    @GeneratedValue(strategy=GenerationType.AUTO)
    private Long id;

    private String name;

    @OneToOne(cascade={CascadeType.PERSIST})
    @JoinColumn(name="passport_id", unique=true) //is unique=true required for bi-directional one-to-one mapping
    private Passport passport;

    public Passport getPassport() {
        return passport;
    }

}

@Entity
public class Passport {

    @Id
    @GeneratedValue(strategy=GenerationType.AUTO)
    private Long id;

    @Column(name="passport_number")
    private String passportNumber;

    @OneToOne(mappedBy="passport")
    private Customer customer;

    public Customer getCustomer() {
        return customer;
    }

}

Hibernate文档说数据库中的 FK列应该被约束为模拟一对一的多重性,但它不会在双向映射中添加unique=true

1 个答案:

答案 0 :(得分:1)

这是因为它不是强制使用Hibernate自动DDL功能。您可以使用增量架构更新脚本,并且与架构相关的注释将毫无用处。坦率地说,我们在内存集成测试中使用它们。

正如您所指出的,JoinColumn应该声明唯一性约束。

相关问题