In the previous tutorial, we have discussed what the different types of generator classes in hibernate are and how they work. The generator classes which are provided by the hibernate are called as predefined generator classes.

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

Except for the assigned generator, remaining all generator classes are work for number type of primary key. If we want to make the primary key as a 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 format, then we can go this custom generator, i.e. If we’re going to generate id as numeric, then we can go with any generator except assigned. Or if we want to make the Id as a string type, we can go with assigned.

What about the combination? Do we have any predefined generators to generate the combination of alphanumeric in hibernate? The answer is No.

Consider a scenario my business requirement is; I need to create primary keys as below:

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

To achieve this, we can go with custom generators in hibernate. To create a user-defined generator class in hibernate (custom generators) our class should implement IdentifierGenerator interface. Not only our custom generator class, but all the pre defined generator classes were also 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

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 Mapping file

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

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 class

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();

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

Database output:

 

Custom Generators in Hibernate

 

After running the CustomIdGenerator.java class for two times, we can get the output like the above database picture.

Download Example