JPA中复合键的唯一约束

时间:2017-03-09 07:50:14

标签: java hibernate jpa constraints composite-key

我有一个带有两个外键的实体,我也想用它作为约束 在JPA中是否有任何方法来定义一个约束,该约束只有在 相同的 FROM_CURRENCY_ID TO_CURRENCY_ID 会重复,但允许值 for FROM_CURRENCY_ID TO_CURRENCY_ID

@Entity
@Table(name="CURRENCY_CONVERSION")
public class CurrencyConversion extends BaseEntity {

    private static final long serialVersionUID = -2440725717151990999L;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "FROM_CURRENCY_ID")
    private Currency fromCurrencyId;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "TO_CURRENCY_ID")
    private Currency toCurrencyId;

    @Column(name = "CURRENCY_RATE", nullable = false)
    private Double rate;
    // getter setters

}

1 个答案:

答案 0 :(得分:2)

@Table注释添加唯一约束定义

@Table(
    uniqueConstraints=
        @UniqueConstraint(columnNames={"column_1", "column_2"})
)
相关问题