How do you create a composite primary key in Spring Data JPA?

A composite primary key spans more than one column, and Spring Data JPA supports it by defining a separate key class that groups those columns, then linking it to the entity with either @EmbeddedId or @IdClass. @EmbeddedId is the more common and cleaner approach.

Key Points

Example

An Enrollment entity linking a student and a course has no single natural primary key, so its uniqueness is defined by the combination of studentId and courseId, modeled as an EnrollmentId class annotated with @Embeddable and referenced from Enrollment via @EmbeddedId.

@Embeddable
public class EnrollmentId implements Serializable {
    private Long studentId;
    private Long courseId;
    // equals(), hashCode(), no-arg constructor
}

@Entity
public class Enrollment {
    @EmbeddedId
    private EnrollmentId id;

    private LocalDate enrolledOn;
}

public interface EnrollmentRepository extends JpaRepository<Enrollment, EnrollmentId> {
}

Interview Tip

A concise interview answer is

I define a separate @Embeddable class holding the composite key's fields, implementing Serializable with proper equals() and hashCode(), and then reference it from the entity using @EmbeddedId. The repository then uses that key class as its ID type, like JpaRepository<Enrollment, EnrollmentId>.

Last updated: 11 November 2026

Previous question: What is the @Id annotation used for?

Next question: What is the @EnableJpaRepositories annotation used for?

More Spring Data JPA interview questions

All Spring Data JPA questions