custom generator class in hibernate | User defined generato

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 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.
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.
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 Mapping file
<?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 class
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:
 
 
After running the CustomIdGenerator.java class for two times, we can get the output like the above database picture.


Custom Generator Classes Example

Custom Generator classes Example in Hibernate
File size: 59 KB
Downloads: 2205


Hibernate One To Many Example (XML Mapping)
Hibernate Named Query with Example
Hibernate Right Join Example
Hibernate One To Many Using Annotations
Hibernate Left Join Example
Hibernate One to One Mapping using primary key (XML)
Singleton Hibernate SessionFactory Example
Spring JdbcTemplate CRUD Application
Generator Classes in Hibernate
Table per Sub Class in Hibernate Inheritance
Table per Class Strategy in Hibernate Inheritance
Table per Concrete Class in Hibernate Inheritance
Hibernate Table per Class strategy Annotations Example
What is Hibernate
Java LinkedList class Example

Hibernate One To Many Example (XML Mapping)
Hibernate Named Query with Example
Hibernate Right Join Example
Hibernate One To Many Using Annotations
Hibernate Left Join Example
Hibernate One to One Mapping using primary key (XML)
Singleton Hibernate SessionFactory Example
Spring JdbcTemplate CRUD Application
Generator Classes in Hibernate
Table per Sub Class in Hibernate Inheritance
Table per Class Strategy in Hibernate Inheritance
Table per Concrete Class in Hibernate Inheritance
Hibernate Table per Class strategy Annotations Example
What is Hibernate
Java LinkedList class Example






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









Mithilesh
November 29, 2020 at 2:28 pm - Reply 

dont use Random class to generate unique number.










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




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





Mithilesh
November 29, 2020 at 2:28 pm - Reply 

dont use Random class to generate unique number.




dont use Random class to generate unique number.
 


Δ
 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