【问题标题】:Unique constraint in OneToOne bi-directional mappingOneToOne 双向映射中的唯一约束
【发布时间】:2014-07-15 05:10:46
【问题描述】:

关系所有者的双向一对一映射是否需要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

【问题讨论】:

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


    【解决方案1】:

    这是因为使用 Hibernate 自动 DDL 功能不是强制性的。您可以拥有增量模式更新脚本,而与模式相关的注释将毫无用处。坦率地说,我们将它们用于内存集成测试。

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-10-26
      • 2017-04-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多