Composite Primary Keys In Hibernate

Composite primary keys means having more than one primary key.

Now lets see what does Composite primary keys means in Hibernate

  • If the table has a primary key then in Entity class we configure that column using @Id annotation and in the hibernate mapping file we need to configure that column by using <id /> element and in
  • In case if the table doesn’t have any primary key, we must configure one column as id (one primary key is must) ,This is mandatory in Hibernate.
  • 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 , in order to configure these primary key columns in the hibernate mapping file we need to use one new element called <composite-id …..></composite-id>
  • In order to configure these primary key columns we need to create a new @Embeddable class containing the PK fields:

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.
  • A composite primary key must be represented and mapped as an embeddable class (EmbeddedId Annotation).
   

Comments are closed