Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JPA - @Column (unique=true) - What is really point of having 'unique' attribute?

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

like image 864
Gaurang Patel Avatar asked May 26 '15 13:05

Gaurang Patel


People also ask

What is @column unique true?

At the table level, we can define unique constraints across multiple columns. JPA allows us to define unique constraints in our code using @Column(unique=true) and @UniqueConstraint. These annotations are interpreted by the schema generation process, creating constraints automatically.

Is @column annotation necessary?

@Column. Let's start with the @Column annotation. It is an optional annotation that enables you to customize the mapping between the entity attribute and the database column.

What is @column in JPA?

In this article, we will discuss how to change the column name in the Spring project using JPA. @Column annotation is used for Adding the column the name in the table of a particular MySQL database. Syntax: @Column(name=”DESC”, nullable=false, length=512)

What is columnDefinition in @column annotation?

columnDefinition definition: The SQL fragment that is used when generating the DDL for the column. columnDefinition default: Generated SQL to create a column of the inferred type.


2 Answers

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.

like image 181
Predrag Maric Avatar answered Sep 22 '22 18:09

Predrag Maric


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.

like image 38
Sajan Chandran Avatar answered Sep 20 '22 18:09

Sajan Chandran