Suppose I am having \'subject\' table
CREATE TABLE subject (id int PRIMARY KEY, name VARCHAR(255) **UNIQUE**)
and associated Mapped Object,
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.
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.
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
.