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

后端 未结 3 1913
别那么骄傲
别那么骄傲 2020-12-29 01:46

Suppose I am having \'subject\' table

CREATE TABLE subject (id int PRIMARY KEY, name VARCHAR(255) **UNIQUE**)

and associated Mapped Object,

相关标签:
3条回答
  • 2020-12-29 02:20

    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.

    0 讨论(0)
  • 2020-12-29 02:36

    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.

    0 讨论(0)
  • 2020-12-29 02:38

    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.

    0 讨论(0)
提交回复
热议问题