Home » Hibernate » Composite Primary Keys In Hibernate

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.
  • If the table has one primary key then in hibernate mapping file we need to configure this column by using <id> element.
  • if the table has multiple primary key columns , in order to configure these primary key we need to use <composite-id=""> element in our hibernate hbm file.

Let us consider there is a need for persisting a Book Object in a table BOOK_INFO.Book class contains properties such as isbn, bookName, authorName, category, price out of which isbn, bookName and authorName are part of a composite primary key fields in the table BOOK_INFO. Steps to implement this requirement is mentioned below.

Tools and Technologies :

  • Java
  • Hibernate 3.6.3.Final
  • Eclipse
  • MySQL 5.5.

Directory structure of the project :

Directory Structure of the project is shown below.

Hibernate composite key

To implement this application , follow the steps mentioned below.

Step 1 . Creating sql query

Create table BOOK_INFO in mysql

create table BOOK_INFO(
isbn integer, 
book_name varchar(50), 
author_name varchar(50), 
category varchar(50),
price decimal, 
primary key (isbn, book_name, author_name));

Step 2 : Creating hibernate Model Class :

Create a package com.javawebtutor.hibernate and create a java class Book in this package and add following code in this class.


package com.jwt.hibernate;

import java.io.Serializable;

public class Book implements Serializable {

	private int isbn;
	private String bookName;
	private String authorName;
	private String category;
	private Double price;

	public int getIsbn() {
		return isbn;

	public void setIsbn(int isbn) {
		this.isbn = isbn;

	public String getBookName() {
		return bookName;

	public void setBookName(String bookName) {
		this.bookName = bookName;

	public String getAuthorName() {
		return authorName;

	public void setAuthorName(String authorName) {
		this.authorName = authorName;

	public String getCategory() {
		return category;

	public void setCategory(String category) {
		this.category = category;

	public Double getPrice() {
		return price;

	public void setPrice(Double price) {
		this.price = price;


Step 3 . Create mapping file for Book class

Create book.hbm.xml in com.jwt.hibernate package to map java class with database tables.


<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
    "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
	<class name="com.jwt.hibernate.Book" table="BOOK_INFO">
			<key-property name="isbn" column="isbn" />
			<key-property name="bookName" column="book_name" />
			<key-property name="authorName" column="author_name" />
		<property name="category" column="category" type="java.lang.String" />
		<property name="price" column="price" type="java.lang.Double" />

In the above hbm file, see line number 9-12,we are using one new element <composite-id>. So if we have a single primary key, we need to use <id> element, but in the case of multiple primary keys, we need to use new element <composite-id>.

Step 4 : Create cfg file :

The configuration file contains informations about the database and mapping file. Conventionally, its name should be hibernate.cfg.xml .Configuration file must be in classpath of your Project.Place this file in src of your project by default it will added to classpath of your project.


<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"

	 	<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
		<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/jwt</property>
		<property name="hibernate.connection.username">root</property>
		<property name="hibernate.connection.password">mukesh</property>
		<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
		<property name="show_sql">true</property>
		<property name="format_sql">true</property>
		<property name="hbm2ddl.auto">update </property>
		<mapping resource="com/jwt/hibernate/book.hbm.xml" />

Step 5 : Create test class :


package com.jwt.hibernate;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;

public class Test {

	public static void main(String[] args) {

		Configuration cfg = new Configuration();

		SessionFactory factory = cfg.buildSessionFactory();
		Session session = factory.openSession();
		Book book = new Book();
		book.setBookName("Head First Java");
		book.setPrice(new Double("500.00"));
		Transaction tx = session.beginTransaction();
		Book book1 = new Book();
		book1.setBookName("Head First Java");
		Book book2 = (Book) session.load(Book.class, book1);
		System.out.println("Category : " + book2.getCategory() + "\nPrice : "
				+ book2.getPrice().toString());



Run the Application :

To run the hibernate application, right click on the Test class -> Run As -> Java Application.

Output in Eclipse :

log4j:WARN No appenders could be found for logger (org.hibernate.cfg.Environment).
log4j:WARN Please initialize the log4j system properly.
        (category, price, isbn, book_name, author_name) 
        (?, ?, ?, ?, ?)
Category : Computers
Price : 500.0

In The Database :

| isbn | book_name       | author_name | category  | price |
|  101 | Head First Java | Kathy       | Computers |   500 |
1 row in set (0.01 sec)

You can download the source code of the example by clicking on the Download link below.

Source + Lib : Download

Previous Next Article

comments powered by Disqus