52

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

Hash
  • 4,647
  • 5
  • 21
  • 39
Gaurang Patel
  • 4,310
  • 6
  • 27
  • 32

3 Answers3

112

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.

Predrag Maric
  • 23,938
  • 5
  • 52
  • 68
  • Thanks! I was trying to find its relevance during runtime.. Do we have any online resource that brief about DDL specific annotations? I tried to search for it but didn't find it.. – Gaurang Patel May 26 '15 at 18:05
  • 1
    Check out section 11.2 in [JPA Specification](http://download.oracle.com/otndocs/jcp/persistence-2_1-edr2-spec/index.html), it lists all annotations and their attributes that are observed in the schema generation process. – Predrag Maric May 27 '15 at 08:12
  • 2
    I know it's been asked a long time ago, but there's also another point to consider regarding the `unique` attribute: unit tests. Even if your production database is not created by JPA, it would be worth using this attribute if your unit tests run against in memory database like H2, since it would take this attribute into account. This way you could write a unit test to validate that unique constraint. – Luis Celestino Jun 29 '21 at 23:13
24

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.

Sai Kishore
  • 326
  • 1
  • 7
  • 16
Sajan Chandran
  • 11,287
  • 3
  • 29
  • 38
0

There's a situation that if the varchar field is too long, say 255 length with utf8mb4 encoded, then the unique constaint won't work even JPA re-create the table with unique-true. Try to set the field with @Column(length=128, unique=ture) and re-create table again to verify. See the top answer in this question for more accurate explanation.