Search code examples
javamysqljpaopenjpa

How to put a unique database constrain correctly – using Alter Table or in JPA annotation?


I work with MySQL/OPENJPA. I have a task to impose uniqueness in one of the table columns. From what I see I can do this in 2 ways.

  1. Use Alter Table <table name> ADD UNIQUE <column name>

OR

  1. Using JPA annotation: @Table(name="<table name>", uniqueConstraints=@Unique(columnNames="<column name>"))

Which way is correct? Or maybe using both at the same time?


Solution

  • JPA annotation will be only used during generation of new db schema (so only if your persistence.xml has ddl-generation create-tables or drop-and-create). It doesn't effect existing tables nor it is checked by JPA.

    So if your DB already exists you need to use ALTER TABLE