MyJavaCode.com

Tutorial and How to Guide on Java Programming. Topics covered include Java Programming Language - Core Java, Spring, Webservices, REST, Hibernate, Maven and Microservices.

  • Core Java
  • REST API’s
  • Spring boot
  • Hibernate
  • Interview Questions
  • Contact Us
  • Projects
  • Offerings

How to Map Composite Key in Hibernate

January 30, 2025 By Prasanna Manjunatha

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.

  • JaCoCo Code Coverage in Springboot Applications : A Comprehensive Guide
  • How to Password Protect a PDF File using Java : A Step-by-Step Guide
  • Automate Audit Fields in Spring Boot with MyBatis: A Generic Solution for CRUD Operations

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.

email
print

About Prasanna Manjunatha

Prasanna is a Toronto based Java Consultant with more than 15 years of Software Development experience. His areas of expertise include Core Java, Spring boot, REST, Microservices, Hibernate, NoSQL, Docker, Kubernetes and AWS.

Currently Trending

Connect with us

  • Facebook
  • GitHub
  • LinkedIn
  • Twitter

TAG CLOUD

Axis2 CodeCoverage Code Coverage cron expression Data Structure Frameworks Hashing HashMap Hibernate IntelliJ java Java Mail jboss jpa 2.1 Maven MyBatis MySQL PDF Quartz REST REST API SOAP Spring boot Springboot SQL Tools Tutorial web service

All time Popular Posts

Copyright © 2025 MyJavaCode.com