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

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 Annotation with Example

Hibernate is an ORM (Object-Relational Mapping) tool which simplifies the application development. Hibernate provides a framework which interacts with the data stored in the databases and it also uses the specifications of the...

2 minutes read.

Hibernate vs. JPA

What is JPA? JPA stands for Java Persistence API, which defines a set of functionalities, standards, and concepts to the ORM tool. It is a framework used to manage relational databases. It is available...

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 vs. JDBC

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...

2 minutes read.

Architecture of Hibernate

Next → Hibernate is an ORM framework with a layered architecture. It consists of many objects, such as a persistent object, sessionfactory object, transaction object, session, etc.  There are mainly three layers in Hibernate...

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 Query Language (HQL)

Hibernate provides its query language called Hibernate Query Language (HQL). HQL is an object-oriented query language, similar to the native SQL language, and it works with persistent objects. It is a database-independent and...

2 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 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.

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 Named Query using Annotation

In annotation-based named query, we use @NamedQuery annotation inside the POJO class. @NamedQuery- It is used to describe a single named query. It consists of four attributes- two of which are compulsory, and...

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 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 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.

Hibernate merge() vs. update()

In Hibernate, both update() and merge() methods are used to convert the detached state object into the persistent state. session.merge() The merge() method is used when we want to change a detached entity into...

2 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 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.

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 Inverse

Hibernate Inverse An Inverse attribute is used to maintain the relationship between the parent and child class object. The inverse attribute is used only with bi-directional mappings such as one-to-many and many-to-many Hibernate mapping. In Hibernate, the...

2 minutes read.