In the context of relational databases, a composite key is a combination of two or more columns in a table that can be used to make the uniqueness of a table row. In this tutorials, we are going to implement how to define a hibernate composite key, and how to map the database composite primary keys in a hibernate mapping. Here is the example for Hibernate composite key:

Hibernate Composite Key Mapping :

Lets create a database table with composite primary key.

SQL Tables
CREATE TABLE `student` (
`studentid` int(11) NOT NULL AUTO_INCREMENT,
`courceid` int(11) NOT NULL,
`studentname` varchar(50) DEFAULT NULL,
`studentAddress` varchar(50) DEFAULT NULL,
PRIMARY KEY (`studentid`,`courceid`)
) ENGINE=InnoDB AUTO_INCREMENT=1

Project Structure :

Hibernate Composite Key Example

Required Dependencies :

pom.xml
<dependencies>
  <!-- Hibernate -->
  <dependency>
    <groupId>org.hibernate</groupId>
    <artifactId>hibernate-core</artifactId>
    <version>4.3.0.Final</version>
  </dependency>
  <!-- MySQL Driver -->
      <dependency>
          <groupId>mysql</groupId>
          <artifactId>mysql-connector-java</artifactId>
          <version>5.0.5</version>
      </dependency>
</dependencies>

HibernateUtility : HibernateUitl.java

HibernateUtil.java
package com.onlinetutorialspoint.util;
import org.hibernate.SessionFactory;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
public class HibernateUtil {   
    private HibernateUtil() {   
    }   
    private static SessionFactory sessionFactory;   
    public static synchronized SessionFactory getInstnce() {      
        if (sessionFactory == null) {         
            Configuration configuration = new Configuration().configure("hibernate.cfg.xml");         
            StandardServiceRegistryBuilder builder = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties());         
            sessionFactory = configuration.buildSessionFactory(builder.build());      
        }      
        return sessionFactory;   
    }
}

Hibernate POJO: Student.java

Student.java
package com.onlinetutorialspoint.beans;
import java.io.Serializable;
public class Student implements Serializable {   
    private static final long serialVersionUID = 1 L;   
    private int studentId;   
    private String studentName;   
    private String studentAddress;   
    private int courceId;   
    public int getStudentId() {      
        return studentId;   
    }   
    public void setStudentId(int studentId) {      
        this.studentId = studentId;   
    }   
    public String getStudentName() {      
        return studentName;   
    }   
    public void setStudentName(String studentName) {      
        this.studentName = studentName;   
    }   
    public String getStudentAddress() {      
        return studentAddress;   
    }   
    public void setStudentAddress(String studentAddress) {      
        this.studentAddress = studentAddress;   
    }   
    public int getCourceId() {      
        return courceId;   
    }   
    public void setCourceId(int courceId) {      
        this.courceId = courceId;   
    }
}

 

To represent the composite key in hibernate, the pojo class should implement the Serializable interface. Otherwise hibernate will throw org.hibernate.MappingException like “Composite-id class must implement Serializable”

Hibernate Mapping File : student.hbm.xml

student.hbm.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC
  "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
  "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
  <class name="com.onlinetutorialspoint.beans.Student" table="student">
    <composite-id>
      <key-property name="studentId" column="studentid" />
      <key-property name="courceId" column="courceid" />
    </composite-id>
    <property name="studentName" />
    <property name="studentAddress" />
  </class>
</hibernate-mapping>
To represent the composite keys, hibernate provides <key-property> tag under the <composite-id> tag.
We can represent each primary key with <key-property> tag, so that all primary keys will be binded with the <composite-id> tag.

Lets Run the Application : Main.java

Main.java
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import com.onlinetutorialspoint.beans.Student;
import com.onlinetutorialspoint.util.HibernateUtil;
public class Main {   
    public static void main(String args[]) {      
        SessionFactory sessionFactory = HibernateUtil.getInstnce();      
        Session session = sessionFactory.openSession();      
        Student student = new Student();      
        student.setStudentId(103);      
        student.setStudentAddress("Hyderabad");      
        student.setStudentName("Johny");      
        student.setCourceId(201);      
        Transaction tx = session.beginTransaction();      
        session.save(student);      
        tx.commit();      
        session.close();   
    }
}

Output:

Terminal
Hibernate: insert into student (studentName, studentAddress, studentid, courceid) values (?, ?, ?, ?)
Hibernate composite key table

Happy Learning 🙂

Download Example

About the Author:

Founder of onlinetutorialspoint.com Love Java, Python, Shell and opensource frameworks. Follow him on twitter and facebook for latest updates.

Leave A Comment