Spring Data JPA Composite Key Mapping Example

Samuel Mumo
2 min readMay 8, 2020

--

A composite key in relational databases is a combination of two columns to form a primary key. This comes in handy when modelling many to many mappings and you need to store extra information in the same table.

For example, in an ecommerce website, you might want to have a table to store product rating by different customers. A customer can rate many products and a product can have many ratings. This can be modelled as a simple many to many relationship between customer and product table. However, we need to store the rating. The table structure will look like this.

| customer_id | product_id | rating |

The ‘customer_id’ is foreign key to customer table and ‘product_id’ is foreign key to product table. The composite key here is ‘customer_id’ and ‘product_id’. Both need to be unique for each row in the table

Implementation in Spring JPA

This example assumes you are already familiar with Spring Data JPA, modelling many to many relationships, many to one and one to many inverse relationships.

We are going to model 3 entity classes. Customer , Product and ProductRating class. I am only going to include the necessary annotations in example code so demonstrate how to add the composite key and model the many to many relationship.

The ProductRating entity class will store the product rating information. Every entity class in JPA must have a primary key. Because our primary key for this entity will be a composite key, we need to create another class that will hold the different parts of the key. This class must meet the following conditions:

  • Have a no arg constructor
  • Implement serializable interface
  • Must define equals() and hashCode() methods
  • Must have @Embeddable annotation

Lets call our class ProductRatingKey in this example. It will contain the following code.

ProductRatingKey class code

The @Data annotation in the above key is a lombok annotation to help in generating boiler plate code for getters and setters. It also generates equals(), toString() and hashCode() methods for us.

Next, let’s create our ProductRating entity that will make use of the composite key that we just created and model the many to many to relationship to Customer and Product entities.

The @EmbeddedId annotation is used to mark the primary key. The @MapsId is used to tie the object to part of the key. We also define many-to-one relationship to product and customer objects. Note, we used @ManyToOne annotation.

Finally, customer and product classes can have a one to many relationship to ProductRating to define a inverse relationship.

customer entity

Finally, let’s define our repository class to fetch data from the ProductRating class.

Hope this short tutorial has helped you learn how implement composite-key in Spring JPA and model many to many relationship using @EmbeddedId and @Embeddable annotations.

--

--