Custom Generator Class in Hibernate

By | 2018-03-13T02:53:25+00:00 October 14th, 2015|Hibernate|1 Comment

In the previous tutorials we have discuss about what are the different types of generator classes in hibernate and how they are works. The generator classes which are provided by the hibernate are called as pre defined generator classes.

When existing generator classes in hibernate (pre defined generator classes) are not suitable for our project requirements, then we can create our own custom generator class.

Except the assigned generator, remaining all generator classes are work for number type of primary key. If we want to make the primary key as string type, then we can define the generator class as assigned.

When we need Custom generator class in hibernate :

If we want to generate a primary key with our own format, then we can go this custom generator i.e. If we want to generate id as numeric then we can go with any generator except assigned. Or if we want to make the Id as string type we can go with assigned.

What about the combination ? Do we have any pre defined generators to generate the combination of alphanumeric in hibernate ? The answer is No. Consider a scenario my business requirement is, I need to generate primary keys as bellow :

"Cust_"<CustomerId>"_Year"
Example :
Cust_001_2014
Cust_002_2014
Cust_003_2015

To achieve this, we can go with custom generators in hibernate. In order to create a user defined generator class in hibernate (custom generators) our class should implement IdentifierGenerator interface. Not only our custom generator class, all the pre defined generator classes were implemented by the IdentifierGenerator interface.

The IdentifierGenerator interface has a single abstract method called generate(). So we need to override generate() method and define our own logic to generate custom Id in the that.

Example for Custom generator class in hibernate :

Create Customer.java


package com.onlinetutorialspoint.pojo;

public class Customer implements java.io.Serializable {

    private String customerId;
    private String customerName;
    private String city;

    public String getCustomerId() {
        return customerId;
    }

    public void setCustomerId(String customerId) {
        this.customerId = customerId;
    }

    public String getCustomerName() {
        return customerName;
    }

    public void setCustomerName(String customerName) {
        this.customerName = customerName;
    }

    public String getCity() {
        return city;
    }

    public void setCity(String city) {
        this.city = city;
    }

}

Create Customer.hbm.xml


<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
    <class catalog="onlinetutorialspoint" name="com.onlinetutorialspoint.pojo.Customer" table="customer">
        <id name="customerId" column="custid" type="string">
            <generator class="com.onlinetutorialspoint.service.CustomIdGenerator"/>
        </id>
        <property name="customerName" column="custname" type="string" length="50"/>
        <property name="city" column="city" type="string" length="50"/>
    </class>
</hibernate-mapping>

Create CustomIdGenerator.java


package com.onlinetutorialspoint.service;

import java.io.Serializable;
import java.util.Calendar;
import java.util.Date;
import java.util.Random;
import org.hibernate.HibernateException;
import org.hibernate.engine.spi.SessionImplementor;

import org.hibernate.id.IdentifierGenerator;

public class CustomIdGenerator implements IdentifierGenerator {

    public int generateCustId() {
        Random random = new Random();
        return random.nextInt(100);
    }

    @Override
    public Serializable generate(SessionImplementor si, Object o) throws HibernateException {

        Date date = new Date();
        
        Calendar calendar = Calendar.getInstance();
        return "Cust_" + this.generateCustId() + "_" + calendar.get(Calendar.YEAR);

    }
}

Create Main.java

package com.onlinetutorialspoint.service;

import com.onlinetutorialspoint.pojo.Customer;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;

public class Main {

    public static void main(String[] args) {
        Configuration configuration = new Configuration();
        configuration.configure("hibernate.cfg.xml");
        SessionFactory factory = configuration.buildSessionFactory();
        Session session = factory.openSession();
        Transaction tx = session.beginTransaction();
        Customer customer = new Customer();
        customer.setCustomerName("Chandra Shekhar");
        customer.setCity("Banglore");
        session.save(customer);
        tx.commit();
        session.close();

    }
}

INFO: Envers integration enabled? : true Hibernate: insert into onlinetutorialspoint.customer (custname, city, custid) values (?, ?, ?)

Database output:

Custom Generators in HibernateAfter running the CustomIdGenerator.java class for two times, we can get the output like above database picture. This is the way we can define custom generator classes in hibernate.

Download Example

About the Author:

Hi Folks, you have reach this so far, that shows you like what you are learning. Then why don't you support us to improve for bettor tutorials by leaving your valuable comments and why not you keep in touch with us for latest updates on your favorite blog @ facebook , twitter , Or Google+ ,

One Comment

  1. tarmizi2001@gmail.com'
    Tarmizi August 6, 2018 at 11:46 am - Reply

    Hy Chandrashekhar,

    Nice tutorial, but how can we implement it with jpa annotation? .
    I have tried as below:
    @GeneratedValue(generator = “polIdGenerator”)
    @GenericGenerator(name = “polIdGenerator”,
    parameters = @Parameter(name = “prefix”, value = “pol”),
    strategy = “id.rekam.medis.generator.PolIdGenerator”)
    @Id
    @Column(name = “ID”)

    But not work.

    Thanks,

    Tarmizi

Leave A Comment