Video in progress
How do you write a composite primary key in Hibernate: `@EmbeddedId` or `@IdClass`?
Both work. With @EmbeddedId the key is a separate @Embeddable object (often a record), while with @IdClass the key fields sit separately in the entity. In both cases the key class must be Serializable and implement equals/hashCode correctly.
📖 Answer
For example, a user's score in a course: the key is (user_id, course_id).
@Embeddable
public class EnrollmentId implements Serializable {
private Long userId;
private Long courseId;
protected EnrollmentId() {}
public EnrollmentId(Long userId, Long courseId) { this.userId = userId; this.courseId = courseId; }
// equals() and hashCode() on both fields
}
@Entity
class Enrollment {
@EmbeddedId
private EnrollmentId id;
@MapsId("userId")
@ManyToOne(fetch = FetchType.LAZY)
private User user;
@MapsId("courseId")
@ManyToOne(fetch = FetchType.LAZY)
private Course course;
private int score;
}
@MapsId ties a field inside the key to the same column as the association, so user_id isn't mapped twice. Hibernate 6.2+ can make a record an @Embeddable too, but with @MapsId Hibernate fills in the key fields itself, so a plain class is safer here.
The @IdClass variant:
@Entity
@IdClass(EnrollmentKey.class)
class Enrollment {
@Id private Long userId;
@Id private Long courseId;
}
It's handier in JPQL (you write e.userId, not e.id.userId), but the key fields are repeated in two places.
I usually choose @EmbeddedId: the key is a single object, and findById(new EnrollmentId(1L, 2L)) reads naturally. But one more thing: if you're designing a new table, a surrogate id plus a unique constraint on (user_id, course_id) is often simpler, with fewer problems with Spring Data save(), merge and REST URLs.
Sign up to mark studied questions and save your progress.