Java.Hibernate.Beginner.When primary key is composite, lets say from 2 columns how does it look ? give example

When a primary key is composite, it means it consists of two or more columns together forming the unique identifier → no single column is enough to uniquely identify the row, but the combination is.


🔹 How does a composite primary key look in SQL?

Example: Suppose you have an enrollment table representing students enrolled in courses. The combination of student_id and course_id uniquely identifies each enrollment:

CREATE TABLE enrollment (
  student_id BIGINT NOT NULL,
  course_id BIGINT NOT NULL,
  enrollment_date DATE,
  grade VARCHAR(10),
  PRIMARY KEY (student_id, course_id), -- composite primary key
  FOREIGN KEY (student_id) REFERENCES student(id),
  FOREIGN KEY (course_id) REFERENCES course(id)
);

🔹 What does it mean?
✅ Neither student_id nor course_id alone guarantees uniqueness.
✅ But together (student_id, course_id) ensures one student can enroll only once in a given course, avoiding duplicate enrollments.


🔹 How does the database enforce it?

  • The DBMS creates a unique index on the pair (student_id, course_id) → duplicate combinations are rejected.
  • Both columns are marked as not null, since primary key columns cannot contain nulls.

🔹 What does the data look like?

student_idcourse_idenrollment_dategrade
11002024-09-01A
21002024-09-01B
11012024-09-02A-

✅ You can see student_id=1 can appear multiple times, but never twice with the same course_id.

🔹 How do you map this in Hibernate?
Using @EmbeddedId or @IdClass

🔹 Example composite PK class for Hibernate with @Embeddable:

@Embeddable
public class EnrollmentId implements Serializable {
    private Long studentId;
    private Long courseId;
    // equals() and hashCode() required
}

And entity:

@Entity
public class Enrollment {
    @EmbeddedId
    private EnrollmentId id;
    private String grade;
}

Key takeaway:
A composite primary key uses two or more columns together as the unique identifier, ensuring no duplicates of the combination — it’s common for join or link tables representing many-to-many relationships (e.g., enrollment).

This entry was posted in Без рубрики. Bookmark the permalink.