Java Interview Questions - ADP
- How to implement composite primary keys 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 can configure in 3 ways as below.
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 can configure in 3 ways as below.
Using @IdClass annotation
@Entity
@IdClass(ProjectId.class)
public class Project {
@Id int departmentId;
@Id long projectId;
:
}Class ProjectId {
int departmentId;
long projectId;
}
Using embeddable class:
@Entity
public class Project {
@EmbeddedId ProjectId id;
:
}
@Embeddable
Class ProjectId {
int departmentId;
long projectId;
}
XML configuration:
<hibernate-mapping>
<class name="str.Product" table="products">
<composite-id>
<key-property name="productId" column="pid" />
<key-property name="proName" column="pname" length="10" />
</composite-id>
<property name="price"/>
</class>
</hibernate-mapping>
Comments
Post a Comment