JPA - @Column(unique = true) - 具有'unique'属性的真正意义是什么? [英] JPA - @Column (unique=true) - What is really point of having 'unique' attribute?

查看:4263
本文介绍了JPA - @Column(unique = true) - 具有'unique'属性的真正意义是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有'主题'表

  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屋!

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