Pages Navigation Menu

Coding is much easier than you think

Composite Primary Keys In Hibernate

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:

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:

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

	private RegistrationId regid;
        // Create Getters and Setters

To persist the entity:

   RegistrationId regId = new RegistrationId();

   StudentEntity student = new StudentEntity(); 

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


About Mohaideen Jamil

Am currently working as a Struts 2 Developer in a reputed IT Organisations. I can help you with teaching Core java and Struts 2. Follow me on Facebook or Google Plus. If you like my tutorials, consider making a donation to this charity, thanks.