JPA中的多个唯一约束 [英] Multiple unique constraints in JPA

查看:397
本文介绍了JPA中的多个唯一约束的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

  @Entity 
@Table(name =person,
uniqueConstraints = @ UniqueConstraint(columnNames = {code,uid}))
public class Person {
// Unique在代码和uid
公共字符串代码;
public String uid;

//用户名
的唯一性public String username;

公共字符串名称;
public String email;
}

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

>的属性 uniqueConstraints 实际上接受这些数组。你的例子只是一个单个元素的数组的缩写。不然的话,它看起来像:

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

只要唯一约束仅基于一个字段,就可以使用 @Column(unique = true)在那一栏。

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

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

解决方案

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.

这篇关于JPA中的多个唯一约束的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆