在Hibernate JPA2上使用唯一约束

如何在hibernate POJO上实现我的唯一约束? 假设数据库不包含任何数据库。

我在@Column()注释中看到了唯一属性,但我无法使其工作?
如果我想将此约束应用于多个列,该怎么办?

基本上,没有数据库支持,您无法实现唯一约束。

@UniqueConstraint@Column unique属性是用于生成相应约束的模式生成工具的指令,它们本身不实现约束。

您可以在插入新实体之前进行某种手动检查,但在这种情况下,您应该了解并发事务可能存在的问题。

因此,在数据库中应用约束是首选。

您可以使用类中的@Table(uniqueConstraints = ...)注释声明唯一约束

 @Entity @Table(uniqueConstraints= @UniqueConstraint(columnNames = {"surname", "name"})) public class SomeEntity { ... } 

在JPA2中,您可以将Unique约束直接添加到字段:

 @Entity @Table(name="PERSON_TABLE") public class Person{ @Id @Column(name = "UUID") private String id; @Column(name = "SOCIALSECURITY", unique=true) private String socialSecurityNumber; @Column(name = "LOGINID", unique=true) private String loginId; } 

恕我直言,更好的是将唯一约束直接分配给属性而不是在表的开始时。

但是,如果需要声明复合唯一键,则在@table注释中声明它是唯一的选择。