JPA - @Column(unique = true) - 具有'unique'属性的真正意义是什么? [英] JPA - @Column (unique=true) - What is really point of having 'unique' attribute?
问题描述
CREATE TABLE主题(id int PRIMARY KEY,name VARCHAR(255)* * UNIQUE **)
和关联的映射对象
@Entity
@Table(name =subject)
public class SubjectDO {
@Id
@Column(name =id)
int id;
@Column(name =name,unique = true)
字符串名称;
...
// Getter-Setter方法
}
当我尝试保存具有重复的'name'的对象时,定义了'unique'和'true',我得到了类似的行为(同样的例外情况)。显而易见,JPA实现除非伸出数据库用于检查。
它的真实用例是什么?
(我在这里假设唯一约束)
unique
in <$仅当您让JPA提供程序为您创建数据库时才使用c $ c> @Column - 它将在指定的列上创建唯一约束。但是,如果您已经拥有数据库,或者一旦创建了数据库,那么 unique
没有任何作用。
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.
What is the real use case for it?
(I am assuming here, unique constraint is defined at Database level too.)
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.
这篇关于JPA - @Column(unique = true) - 具有'unique'属性的真正意义是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!