Hibernate中嵌入式成员的唯一约束

时间:2014-07-09 18:29:06

标签: java hibernate jpa

是否可以在Hibernate中为嵌入式类的成员定义唯一约束?

我需要确保Nested :: i1和Nested :: i2作为一对(组合)是唯一的

@Entity
@Table( uniqueConstrains = ???)
public class Widget {
   @Id
   private int id;

   @Embedded
   Nested nested;
}

@Embeddable
public class Nested {
    private int i1;
    private int i2;
}

1 个答案:

答案 0 :(得分:5)

可以使用:

@Entity
@Table(uniqueConstraints = { @UniqueConstraint(columnNames = {"i1", "i2"})})
public class Widget {

这将导致CREATE SQL(postgresql示例)

create table Widget 
(  id int8 not null,
   i1 int8, 
   i2 int8 ,
   primary key (id),
   unique (i1, i2)
) 

可选 - 当您在一个文件中添加@AttributeOverride注释时,可能会更加简洁和可读 - 两个属性的列名称

@AttributeOverrides({
        @AttributeOverride(name = "i1", column = @Column(name = "i1")),
        @AttributeOverride(name = "i2", column = @Column(name = "i2"))
})
@Embedded
Nested nested;