Java JPA - @Column (unique=true) - 拥有“unique”属性的真正意义是什么?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/30460596/
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
JPA - @Column (unique=true) - What is really point of having 'unique' attribute?
提问by Gaurang Patel
Suppose I am having 'subject' table
假设我有“主题”表
CREATE TABLE subject (id int PRIMARY KEY, name VARCHAR(255) **UNIQUE**)
and associated Mapped Object,
和关联的映射对象,
@Entity
@Table(name="subject")
public class SubjectDO {
@Id
@Column(name="id")
int id;
@Column(name="name", unique=true)
String name;
...
// Getter-Setter methods
}
When I try to save object having duplicate 'name' with and without 'unique=true' defined, I am getting similar behavior (same exception.) And it is obvious that JPA implementation can't really do anything unless reaching out to DB for checking.
当我尝试保存具有和未定义“unique=true”的重复“name”的对象时,我得到了类似的行为(相同的例外。)而且很明显,除非与 DB 联系,否则 JPA 实现无法真正做任何事情检查。
What is the real use case for it?
它的真正用例是什么?
(I am assuming here, unique constraint is defined at Database level too.)
(我在这里假设,唯一约束也在数据库级别定义。)
采纳答案by Predrag Maric
unique
in @Column
is used only if you let your JPA provider create the database for you - it will create the unique constraint on the specified column. But if you already have the database, or you alter it once created, then unique
doesn't have any effect.
unique
in@Column
仅在您让 JPA 提供程序为您创建数据库时使用 - 它将在指定的列上创建唯一约束。但是,如果您已经拥有该数据库,或者您在创建后对其进行了更改,则unique
不会产生任何影响。
回答by Sajan Chandran
unique=true
in @Column
annotation will be used only in DDL generation
, it doesn't have any impact during runtime. The actual uniqueness checks happens in the database
.
unique=true
in@Column
注释将仅用于 in DDL generation
,它在运行时没有任何影响。实际的唯一性检查发生在database
.