Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unique Key Constraint in Spring Data Jpa

How to make a field unique in pojo using spring data jpa?I know how to do that using jpa

For reference: multi column constraint with jpa

If there is a way, is it possible to use with spring boot?

like image 345
Karthikeyan Soundararaj Avatar asked Mar 15 '17 22:03

Karthikeyan Soundararaj


People also ask

How do you make a unique field in JPA?

A unique constraint can be either a column constraint or a table constraint. 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.

What is @ID annotation in JPA?

@Id annotation is the JPA is used for making specific variable primary key.

How foreign key is defined in JPA entity?

Implementing With a Foreign Key in JPA. Note that we place the @OneToOne annotation on the related entity field, Address. Also, we need to place the @JoinColumn annotation to configure the name of the column in the users table that maps to the primary key in the address table.


2 Answers

Use the @UniqueConstraint annotation to specify that a unique constraint is to be included in the generated DDL for a primary or secondary table.

Alternately, to ensure a field value is unique you can write

@Column(unique=true)
String myField;
like image 140
Rahul Avatar answered Oct 02 '22 17:10

Rahul


With Spring Data JPA you are using JPA, so you specify the unique constraint using JPA. Nothing special from Spring Boot or Spring Data on that front.

like image 34
Jens Schauder Avatar answered Oct 02 '22 16:10

Jens Schauder