Pages Navigation Menu

Coding is much easier than you think

Composite Primary Keys In Hibernate


 
If the table has a primary key then in Entity class we configure that column using @Id annotation. Even when the table doesn’t need a primary key, we must configure one column as id (one primary key is must).
 
Now If the database table has more than one column as primary key then we call it as composite primary key, so if the table has multiple primary key columns , then in order to configure these primary key columns we need to create a new @Embeddable class containing the PK fields:
 

@Embeddable
public class RegistrationId implements Serializable{

	@Column(name = "STUDENT_ID")
	private int studentId;

	@Column(name = "DEPARTMENT")
	private String department;

        // Create getters and Setters
}

 
And we should use it in the @Entity as a @EmbeddedId:
 

@Entity
@Table(name = "STUDENT")
public class StudentEntity {

	@EmbeddedId
	private RegistrationId regid;
        ...
        // Create Getters and Setters
}

 
To persist the entity:
 

   RegistrationId regId = new RegistrationId();
   regId.setStudentId(1);
   regId.setDepartment("ECE");

   StudentEntity student = new StudentEntity();
   student.setRegid(regId);
	
   session.save(student);

 
The following rules must apply for composite primary keys:

  • The primary key class must be public.
  • If property-based access is used, the properties of the primary key class must be public or protected.
  • The primary key class must be serializable. We shall explore the reason for implementing this interface in our upcoming tutorial.
  • A composite primary key must be represented and mapped as an embeddable class (EmbeddedId Annotation).

We shall explore the concept behind this composite primary keys in the next article.
 

Other Hibernate tutorial from our Blog