Hibernate Composite Primary Key

Hibernate Composite Primary Key

A Composite Primary Key is a combination of one or more columns that forms a primary key. When a database table contains more than one primary key column, it is known as a composite primary key or a composite key.

Composite keys are a group of columns in the database, whose values together make a unique value.

We can create a composite key in two ways:

  • Using an XML file
  • Using annotations

Using an XML File

We can create a composite key using an XML mapping file. In that mapping file, we are using a <composite-id>…<composite-id/> tag to declare a composite key. All the primary key objects of the POJO class are defined inside the composite key tag.

Syntax of <composite-id>


      
      
  

With Hibernate 5 (version 5 and above), composite key using annotations are more popular than an XML file.  Hence, we are going to create an example of a composite key using annotation.

Using annotations

We can create a composite key using @Embeddable annotation. It is used in that POJO class which contains the information of all the primary keys.

@Embeddable- It specifies a class whose objects are stored as an intrinsic part of an owing entity. And also, it shares the identity of the entity. Every field of the embedded object is mapped with the database table. It is available in javax.persistence package. 

In order to define composite keys, we should implement the given rules:

  1. The composite key class should be public.
  2. The composite key class must implement the Serializable interface.
  3. The class must have a constructor.
  4. The class should have equals()  and hashCode() methods.

Syntax of @Embeddable

@Embeddable
 public class Ck_accId implements Serializable{
             private int user_id;
             private int acc_id;
    } 

Example of Composite Key using annotation

Here, we are going to create an example of a composite key. In this example, we are taking two classes, Account.java and Ck_accId.java. The Account.java is a pure POJO class, whereas Ck_accId.java is a composite key class.

Following are the steps to create a composite key:

Account.java

import javax.persistence.Entity;
 import javax.persistence.Id;
 @Entity
 public class Account {
             Ck_accId ck_accid;
             private int acc_bal;
             @Id 
               public Ck_accId getCk_accid() {
                         return ck_accid;
             }
               public void setCk_accid(Ck_accId ck_accid) {
                         this.ck_accid = ck_accid;
             }
               public int getAcc_bal() { 
                         return acc_bal;
             }
               public void setAcc_bal(int acc_bal) {
                         this.acc_bal = acc_bal;
             }
     } 

The Account.java contains an object of Ck_accId class. It also contains a variable named acc_bal.

Ck_accId.java

import java.io.Serializable;
 import javax.persistence.Embeddable;
 @Embeddable
 public class Ck_accId implements Serializable{
             private int user_id;
             private int acc_id;
             public Ck_accId(int user_id, int acc_id) {
                         super(); 
                         this.user_id = user_id;
                         this.acc_id = acc_id;
             }
             public int getUser_id() {
                         return user_id;
             }
             public void setUser_id(int user_id) { 
                         this.user_id = user_id;
             }
             public int getAcc_id() {
                         return acc_id;
             }
             public void setAcc_id(int acc_id) { 
                         this.acc_id = acc_id;
             }
             @Override
             public int hashCode() {
                         final int prime = 31;
                         int result = 1;
                         result = prime * result + acc_id; 
                         result = prime * result + user_id;
                         return result;
             }
             @Override
             public boolean equals(Object obj) {
                         if (this == obj)
                                     return true;
                         if (obj == null) 
                                     return false;
                         if (getClass() != obj.getClass())
                                     return false;
                         Ck_accId other = (Ck_accId) obj;
                         if (acc_id != other.acc_id)
                                     return false; 
                         if (user_id != other.user_id)
                                     return false;
                         return true;
             }
   } 

The Ck_accId.java is an Embedded class. It contains two primary key variables, user_id, and acc_id.

hibernate.cfg.xml

  
   
   
       
         create  
         org.hibernate.dialect.MySQL5Dialect 
         jdbc:mysql://localhost:3306/test2
         com.mysql.jdbc.Driver
         root  
         root   
         
       
       
    

The hibernate.cfg.xml contains the information of the database and the mapping class (com.app.Composite_key.Account).

App.java

import org.hibernate.Session;
 import org.hibernate.SessionFactory;
 import org.hibernate.cfg.Configuration;
 public class App 
 {
     public static void main( String[] args )
     {
        Configuration cfg = new Configuration(); 
        cfg.configure("hibernate.cfg.xml");
        SessionFactory fact= cfg.buildSessionFactory();
        Session sess = fact.openSession();
        sess.beginTransaction();
        Ck_accId id1= new Ck_accId(10, 1016);
         Account acc= new Account();
         acc.setCk_accid(id1);
         acc.setAcc_bal(8100); 
        Ck_accId id2= new Ck_accId(11, 1020);
        Account acc2 = new Account();
        acc2.setCk_accid(id2);
        acc2.setAcc_bal(7200);
        sess.save(acc); 
        sess.save(acc2);
        sess.getTransaction().commit();
        System.out.println("created");
        sess.close();
     }
 } 

The App.java is the main class, contains the main() method.

OUTPUT

contains the main() method

Database Table- Account


Related Topics

Hibernate N+1 Select Problem

Hibernate N + 1 Select Problem The N + 1 Select problem is a performance issue in Hibernate. In this problem, a Java application makes N + 1 database calls (N = number...

4 minutes read.

Hibernate Inheritance - Single Table

Hibernate Inheritance In this inheritance strategy, only one table is created for all the classes involved in the hierarchy with an additional column known as a discriminator column. The discriminator column helps indifferentiating between...

3 minutes read.

Hibernate Inheritance Joined Table

In this inheritance strategy, mapping of the child class fields is done with the common fields of the parent class in a separate table. In other words, the common entities between the child...

3 minutes read.

Hibernate SessionFactory

Next → Hibernate SessionFactory A SessionFactory is an interface in Hibernate that create the instances of Session interface. It is a heavy weight object, and it is usually created during the application...

3 minutes read.

Lazy Loading in Hibernate

Lazy loading is a fetching technique used for all the entities in Hibernate. It decides whether to load a child class object while loading the parent class object. When we use association mapping...

3 minutes read.

Hibernate Features

1. Lightweight Hibernate is a lightweight framework as it does not contains additional functionalities; it uses only those functionalities required for object-relational mapping. It is a lightweight framework because it uses persistent...

2 minutes read.

Hibernate Lifecycle

Hibernate Lifecycle In Hibernate, the mapped instances of the entity classes have a lifecycle. Either we can create a new object, or we can fetch the existing data from the database. The value objects do...

3 minutes read.

Hibernate Configuration Properties

Hibernate Configuration Hibernate Configuration is a Java class, which allows a Java application to specify configuration parameters used in the application. As Hibernate is designed to serve in different environments, it needs a broad...

6 minutes read.

Hibernate Second-Level Cache

The Second-level cache is related to the SessionFactory object. Once the SessionFactory is closed, all the second-level cache data associated with it will be lost. The cache manager will also get closed. Cache provider The...

5 minutes read.

Hibernate History and Versions

Next → History of Hibernate Hibernate was developed in 2001 by Gavin king with his colleagues from Circus Technologies. The main aim was to provide better persistence capabilities than those of EJB2, by reducing the...

2 minutes read.

Hibernate Named Query Using XML

A named query is a technique used to assemble all the queries (Native SQL and HQL) in a specific location and refer them by some name. It helps in reducing the mess...

3 minutes read.

Hibernate first Example

Now we are going to create the first example in Hibernate. We will proceed step by step to develop the first Java application in Hibernate. The steps are listed below:- Create the POJO...

2 minutes read.

Cascade in Hibernate

Cascading is a feature in Hibernate, which is used to manage the state of the mapped entity whenever the state of its relationship owner (superclass) affected. When the relationship owner (superclass) is saved/...

3 minutes read.

Hibernate Dialects

Hibernate Dialects Dialect is a Java class available in org.hibernate.dialect package, which helps to map Java Application with the database. To interact with the database, we need to define the required database dialect in...

2 minutes read.

Hibernate Tutorial

What is Hibernate? Hibernate is an Object-Relational Mapping (ORM) tool which reduces the difficulty in the application development. Hibernate provides a framework that interacts with the data stored in the databases. It also uses...

3 minutes read.

Hibernate Web Application with Example

Let us create a hibernate web Application. Here we need JSP file for presentation. There are steps given below for the web app creation. index.jsp This page will show a registration form. It takes the...

2 minutes read.

Dirty Checking in Hibernate

Dirty checking is an essential concept of Hibernate. The Dirty checking concept is used to keep track of the objects. It automatically detects whether an object is modified (or not) or wants to...

6 minutes read.

Hibernate get() vs. load()

Hibernate methods, get() and load() both are provided by the Session interface and used to retrieve the objects from the database. Session.get() The session.get() method is used to fetch a persistent object of the...

2 minutes read.

Hibernate Web Application Example

Web Application Example with Hibernate In this section, we create a hibernate web Application. Here we are using a JSP file for presentation. Example of creating a web application using hibernate index.jsp This page will show a...

2 minutes read.

Hibernate Many-to-Many Mapping

Many-to-Many Hibernate Mapping with Example In Many-to-Many association mapping, more than one objects of a persistent class are associated with more than one objects of another persistent class. For example, many (categories) are related to...

3 minutes read.