In this blog, we are going to learn composite primary key in spring data JPA with two annotations @IdClass and @EmbeddedId.
What is Composite Primary Key?
A Composite Primary Key or simply called a composite key is primary key with two or more than two columns.
We have two ways of defining composite keys(A multi column primary key).
- @IdClass Annotation
- @EmbeddedId Annotation
- The class for this composite key must be public
- It must implement Serializable interface
- It must contain equals() and hashcode() methods.
- It must also contains a no arguments contructor.
Lombok Annotations
Defining Entities
Using @IdClass Annotation
Let us create our UserPost Entity and our composite key class UserPostId.
On the top of our UserPost Entity, we use @IdClass annotation and pass UserPostId class as argument. We need to have our composite key columns annotated with @Id annotation in UserPost Entity class.
We need to have our composite columns in the Composite Key class.
Using @EmbeddedId Annotation
Let us create our UserPost Entity and our composite key class UserPostId.
We use @Embedabble annotation on the top of our composite key class and in our entity class, there is no need to declare these fields again, instead we define a variable with UserPostId userPostId with @EmbeddedId annotation.
Post a Comment