most of the cases, identifier (primary key) of the entity will be a single attribute. but there will be some cases where the primary key of the entity will be comprised by several attributes. In other words, primary key will consist of more than one column. if the primary key consist of more than one attribute/column, we called it as composite primary key or compound primary key.
In hibernate, there are three ways that can be used to create compound primary key in a entity class using annotations. In all of these three scenarios, it will be required to create a separate class for the compound primary key.
1. Compound primary key with @Embeddable annotation
mark the compound primary key (PK) class with @Embeddable annotation and add the instance of the PK class to the entity class as a normal property. then mark it with @Id annotation as usual.
2. Compound Primary key with @EmbeddableId annotation
create the compound PK class as POJO (Plain Old Java Object) and add it as a normal property for the Entity class. then mark that instance with @EmbeddableId annotation.
3. Compound Primary key with @IdClass annotation
declare the compound primary key class with @IdClass annotation and add the all primary key properties of that class to the entity class as normal properties. then mark all the added primary key properties with @Id annotation.
Hope this will be helpful for you!
Cheers
Chathuranga Tennakoon
www.chathurangaonline.com
In hibernate, there are three ways that can be used to create compound primary key in a entity class using annotations. In all of these three scenarios, it will be required to create a separate class for the compound primary key.
1. Compound primary key with @Embeddable annotation
mark the compound primary key (PK) class with @Embeddable annotation and add the instance of the PK class to the entity class as a normal property. then mark it with @Id annotation as usual.
2. Compound Primary key with @EmbeddableId annotation
create the compound PK class as POJO (Plain Old Java Object) and add it as a normal property for the Entity class. then mark that instance with @EmbeddableId annotation.
3. Compound Primary key with @IdClass annotation
declare the compound primary key class with @IdClass annotation and add the all primary key properties of that class to the entity class as normal properties. then mark all the added primary key properties with @Id annotation.
Hope this will be helpful for you!
Cheers
Chathuranga Tennakoon
www.chathurangaonline.com