Spring Boot JPA Composite Key Example | @EmbeddedId vs @IdClass
In JPA, a composite key is a primary key that consists of multiple columns. There are two ways to define composite keys:
- Using
@Embeddable
and@EmbeddedId
(Recommended) - Using
@IdClass
(Alternative Approach)
We will cover both approaches with examples in a Spring Boot application using Spring Data JPA.
Approach 1: Using @Embeddable
and @EmbeddedId
(Recommended)
This is the preferred method because it allows better encapsulation of key fields.
Step 1: Create a Spring Boot Project
Use Spring Initializr to create a new project with the following dependencies:
✅ Spring Web
✅ Spring Data JPA
✅ H2 Database (for testing)
Step 2: Define the Composite Key Class
This class represents the primary key.
✔️ Key Points:
@Embeddable
marks this class as an embeddable composite key.- Implements
Serializable
(mandatory for composite keys). - Overrides
equals()
andhashCode()
to ensure proper key comparison.
Step 3: Create the Entity with @EmbeddedId
This entity class uses the composite key.
✔️ Key Points:
@EmbeddedId
is used to specify the composite key.- The
id
field is an instance ofOrderKey
.
Step 4: Create the Repository Interface
✔️ Key Points:
JpaRepository<Order, OrderKey>
→ UsesOrderKey
as the ID type.
Step 5: Create a Service Layer
✔️ Key Points:
- Saves and retrieves orders using the composite key.
Step 6: Create a Controller
✔️ Key Points:
- Exposes REST API for saving and retrieving orders using a composite key.
Step 7: Run and Test
Save an Order
Retrieve an Order
Approach 2: Using @IdClass
(Alternative)
If you don’t want to use @EmbeddedId
, you can use @IdClass
.
Step 1: Define the Composite Key Class
Step 2: Modify the Entity
✔️ Key Points:
@IdClass(OrderKey.class)
maps multiple@Id
fields to a primary key.
Conclusion
- ✅ Use
@EmbeddedId
when you want a clean encapsulated key. - ✅ Use
@IdClass
when you prefer separate primary key fields inside the entity.