JPA 中的多个惟一约束

有没有一种方法可以使用 JPA 指定在不同的列集上应该有多个唯一的约束?

@Entity
@Table(name="person",
uniqueConstraints=@UniqueConstraint(columnNames={"code", "uid"}))
public class Person {
// Unique on code and uid
public String code;
public String uid;


// Unique on username
public String username;


public String name;
public String email;
}

我看到了一个特定于 hibernate 的注释,但是我试图避免使用特定于供应商的解决方案,因为我们仍然在 hibernate 和 datanucleus 之间做出选择。

56798 次浏览

The @Table's attribute uniqueConstraints actually accepts an array of these. Your example is just a shorthand for an array with a single element. Otherewise it would look like:

@Table(name="person",  uniqueConstraints={
@UniqueConstraint(columnNames={"code", "uid"}),
@UniqueConstraint(columnNames={"anotherField", "uid"})
})

Whenever the unique constraint is based only on one field, you can use @Column(unique=true) on that column.