Hibernate Composite Key Mapping Example - onlinetutorialspoint

PROGRAMMINGJava ExamplesC Examples
Java Examples
C Examples
C Tutorials
aws
JAVAEXCEPTIONSCOLLECTIONSSWINGJDBC
EXCEPTIONS
COLLECTIONS
SWING
JDBC
JAVA 8
SPRING
SPRING BOOT
HIBERNATE
PYTHON
PHP
JQUERY
PROGRAMMINGJava ExamplesC Examples
Java Examples
C Examples
C Tutorials
aws
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:
Lets create a database table with composite primary key.
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 : 
 Required Dependencies :
<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
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
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;   
    }
}
 
Hibernate Mapping File : 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>

Lets Run the Application : 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();   
    }
}
Hibernate: insert into student (studentName, studentAddress, studentid, courceid) values (?, ?, ?, ?)
 Happy Learning 🙂


Hibernate-Composite Key-Example

File size: 17 KB
Downloads: 943


Hibernate One to One Mapping using primary key (XML)
One to One Mapping in Hibernate using foreign key (XML)
Hibernate Filter Example Xml Configuration
hbm2ddl.auto Example in Hibernate XML Config
Hibernate Native SQL Query Example
Many to One Mapping in Hibernate Example
Hibernate Many to Many Mapping Example (XML)
Hibernate One To Many Example (XML Mapping)
hibernate update query example
How to convert Java Object to JSON
Hibernate session differences between load() and get()
Generator Classes in Hibernate
Calling Stored Procedures in Hibernate
HQL update, delete Query Example
Basic Hibernate Example with XML Configuration

Hibernate One to One Mapping using primary key (XML)
One to One Mapping in Hibernate using foreign key (XML)
Hibernate Filter Example Xml Configuration
hbm2ddl.auto Example in Hibernate XML Config
Hibernate Native SQL Query Example
Many to One Mapping in Hibernate Example
Hibernate Many to Many Mapping Example (XML)
Hibernate One To Many Example (XML Mapping)
hibernate update query example
How to convert Java Object to JSON
Hibernate session differences between load() and get()
Generator Classes in Hibernate
Calling Stored Procedures in Hibernate
HQL update, delete Query Example
Basic Hibernate Example with XML Configuration
 


Δ
 Hibernate – Introduction
 Hibernate – Advantages
 Hibernate – Download and Setup
 Hibernate – Sql Dialect list
 Hibernate – Helloworld – XML
 Hibernate – Install Tools in Eclipse
 Hibernate – Object States
 Hibernate – Helloworld – Annotations
 Hibernate – One to One Mapping – XML
 Hibernate – One to One Mapping foreign key – XML
 Hibernate – One To Many -XML
 Hibernate – One To Many – Annotations
 Hibernate – Many to Many Mapping – XML
 Hibernate – Many to One – XML
 Hibernate – Composite Key Mapping
 Hibernate – Named Query
 Hibernate – Native SQL Query
 Hibernate – load() vs get()
 Hibernate Criteria API with Example
 Hibernate – Restrictions
 Hibernate – Projection
 Hibernate – Query Language (HQL)
 Hibernate – Groupby Criteria HQL
 Hibernate – Orderby Criteria
 Hibernate – HQLSelect Operation
 Hibernate – HQL Update, Delete
 Hibernate – Update Query
 Hibernate – Update vs Merge
 Hibernate – Right Join
 Hibernate – Left Join
 Hibernate – Pagination
 Hibernate – Generator Classes
 Hibernate – Custom Generator
 Hibernate – Inheritance Mappings
 Hibernate – Table per Class
 Hibernate – Table per Sub Class
 Hibernate – Table per Concrete Class
 Hibernate – Table per Class  Annotations
 Hibernate – Stored Procedures
 Hibernate – @Formula Annotation
 Hibernate – Singleton SessionFactory
 Hibernate – Interceptor
 hbm2ddl.auto Example in Hibernate XML Config
 Hibernate – First Level Cache