Java JPA 中的多个唯一约束

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3404853/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 23:00:22  来源:igfitidea点击:

Multiple unique constraints in JPA

javahibernatejpaormdatanucleus

提问by Jacob

Is there a way to specify using JPA that there should be multiple unique constraints on different sets of columns?

有没有办法使用 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;
}

I have seen a hibernate specific annotation but I am trying to avoid vendor specific solutions as we are still deciding between hibernate and datanucleus.

我看到了一个特定于休眠的注释,但我试图避免供应商特定的解决方案,因为我们仍在决定休眠和 datanucleus 之间。

采纳答案by Bozho

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

所述@Table的属性uniqueConstraints实际接受的这些阵列。您的示例只是具有单个元素的数组的简写。否则它看起来像:

@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.

当唯一约束仅基于一个字段时,您可以@Column(unique=true)在该列上使用。