Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

@Column(unique=true) does not seem to work

Even though I set the attribute to be @Column(unique=true), I still insert a duplicate entry.

@Entity public class Customer {      @Id     @GeneratedValue(strategy = GenerationType.AUTO)     private Long id;      @Column(unique=true )     private String name;      ... } 

I set the name using regular EL in JSF. I did not create table using JPA

like image 562
Thang Pham Avatar asked Aug 16 '10 18:08

Thang Pham


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.

How do I make a column unique in an existing table?

Syntax to add UNIQUE to an existing field. alter table yourTableName add UNIQUE(yourColumnName); Applying the above syntax in order to add UNIQUE to column 'name'. Now we cannot insert duplicate records into the table, since we have set the field to be unique.

What is true about unique clause in MySQL?

The UNIQUE constraint ensures that all values in a column are different. Both the UNIQUE and PRIMARY KEY constraints provide a guarantee for uniqueness for a column or set of columns. A PRIMARY KEY constraint automatically has a UNIQUE constraint.

How do you make a varchar column unique?

In the Object Explorer under the table right-click the Indexes folder and choose New Index... . In the window that appears enter Index name: , tick the Unique checkbox and add your email field from the Add... button then click OK.


1 Answers

The unique=true element of the Column annotation and / or the UniqueConstraint annotation that can be used at the table level are used to specify that a unique constraint is to be included in the generated DDL.

In other words, they don't do anything during the runtime, the verification is left to the database (which makes sense as unicity can't be tested at the Java level reliably1) and if for whatever reason you don't have the corresponding constraint(s) defined at the database level, nothing will happen.

Add the constraint manually:

ALTER TABLE Customer ADD CONSTRAINT customer_name_unq UNIQUE (name); 

See also

  • JPA 1.0 specification
    • 9.1.4 UniqueConstraint Annotation
    • 9.1.5 Column Annotation
  • MySQL Documentation
    • 12.1.7. ALTER TABLE Syntax

1 Unless you acquire a table lock (ouch!), you can't check for unicity with a SQL query in a concurrent environment.

like image 154
Pascal Thivent Avatar answered Sep 21 '22 15:09

Pascal Thivent