spring data jpa find by composite primary key


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). 

  1. @IdClass Annotation
  2. @EmbeddedId Annotation

However, there are some requirements in order to use these annotations. 

  • 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


We can Initialize a Spring boot project just like shown in this blog and include lombok maven dependency. 
In case you are unfamiliar with lombok, it is a java library used to populate boiler plate code with the help of annotations. 

@Data annotation populates Getters, Setters, HashCode and Equals methods. 

We also use @NoArgsConstructor annotation too.


Defining Entities

Let us assume we have User Entity and Post Entity. I don't want to do any joins. 
So, we create a new Entity UserPost which contains both userId and postId. 

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

Same as above, we need an Entity and composite key class.

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.



Custom query using @Query on our Jpa Repository

The difference while using custom query using @Query Annotation is we need to mention the field name of our composite class additionally wherein while using Id, we can mention the field name inside our composite key class directly. Below are find by composite key queries look like.


Post a Comment