Composite key (or Composite Primary Key) cannot be mapped directly in hibernate like how we map the normal primary key’s using @Id annotation attribute. We will have to use @Embedabble & @EmbeddedId annotation attributes to map composite key.
Below is an example Java program to understand how to map composite primary key in Hibernate using annotations,
import javax.persistence.Column;
import javax.persistence.Embeddable;
@Embeddable
public class ProductPK implements Serializable
{
@Column(name="product_code")
private int productCode;
@Column(name="product_category")
private String productCategory;
public int getProductCode()
{
return productCode;
}
public void setProductCode(int productCode)
{
this.productCode = productCode;
}
public String getProductCategory()
{
return productCategory;
}
public void setProductCategory(String productCategory)
{
this.productCategory = productCategory;
}
}
import javax.persistence.Column;
import javax.persistence.EmbeddedId;
import javax.persistence.Entity;
import javax.persistence.Table;
@Entity
@Table(name="product")
public class Product
{
@EmbeddedId
ProductPK productPK;
@Column(name="description")
private String description;
public ProductPK getProductPK()
{
return productPK;
}
public void setProductPK(ProductPK productPK)
{
this.productPK = productPK;
}
public String getDescription()
{
return description;
}
public void setDescription(String description)
{
this.description = description;
}
}
In the above code, we are creating a class called ProductPK and marking it as Embeddable. In the Product class, we are embedding the ProductPK class as a Composite Primary Key.