Posts

Showing posts with the label Spring Boot JPA Composite Key Example | @EmbeddedId vs @IdClass

Spring Boot JPA Composite Key Example | @EmbeddedId vs @IdClass

Image
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. package com.example.demo.model; import jakarta.persistence.Embeddable; import java.io.Serializable; import java.util.Objects; @Embeddable public class OrderKey implements Serializable { private Long orderId; private Long productId; public OrderKey() {} pub...