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
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.
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.
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.
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.
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);
1 Unless you acquire a table lock (ouch!), you can't check for unicity with a SQL query in a concurrent environment.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With