Tuesday , November 21 2017
Home / Hibernate / Generator Classes in Hibernate

Generator Classes in Hibernate

By knowingly or unknowingly, we have been using the generator classes in hibernate since our first basic application. But generators are the one of the most important concept to understand the basics of hibernate.

Hibernate provides different types of predefined generator classes, to represent the primary key column in database. The Generator classes generates an Id value for an object, which is going to be insert in database as a primary key.

To generate the primary key value, hibernate uses generators concept. Below are the different types of predefined generator classes in hibernate.

Predefined Generator Classes :

Hibernate has given some predefined generator classes listed below.

  • assigned
  • increment
  • sequence
  • hilo
  • identity
  • native
  • foreign and
  • uuid

The above classes are the some important predefined generator classes in hibernate, we need to discuss above all in detailed manner. If your requirement doesn’t satisfy the above all generators, don’t worry !,  we can implement our own generator classes in hibernate.

How to use Hibernate Generator classes :

We can use the above all possible generator classes in our application as per our requirement. To represent the generator class, hibernate provided  <generator> tag, it is a sub element of <id>. We need to define these elements in the mapping file i.e. (hbm.xml) to represent the Id property of pojo class.

Hibernate has provided shortcut names for each predefined generator classes. So in hbm.xml we need to configure a shortcut name with in a <generator> tag under <id> tag.

Below are the detailed usage of every generator class in hibernate.

assigned generator:

assigned is a shortcut name given for the Assigned class.

Assigned class returns same id set by the programmer to hibernate and hibernate will store an object with that Id in database.

If we don’t map the generator class for id in hbm.xml file then by default assigned generator is mapped to it.

<id name="studentId" column="sid">/> 
OR 
<id name="studentId" column="sid">
            <generator class="assigned"/>
</id> 

On the above example both syntaxes are same for the assigned generator.

increment generator :

increment is a shortcut name for IncrementGenerator class. When we set the generator class as increment, then id set by the programmer for an object will not be considered by hibernate.


<id name="studentId" column="sid">
            <generator class="increment"/>
</id>

When we configure the generator class as increment, the IncrementGenerator class reads max value of the existing ids in database table and then increments it by one and returns the id value to hibernate.

Formula : max(id)+1

Example :

Student.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.Student" table="student">
        <id name="studentId" column="sid">
            <generator class="increment"/>
        </id>
        <property name="name" type="string">
            <column length="50" name="name"/>
        </property>
        <property name="rollNumber" type="java.lang.Integer">
            <column name="rollnumber"/>
        </property>
    </class>
</hibernate-mapping>

Cleint class : Main.java


package com.onlinetutorialspoint.service;

import com.onlinetutorialspoint.pojo.Student;
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(&quot;hibernate.cfg.xml&quot;);
        SessionFactory factory = configuration.buildSessionFactory();
        Session session = factory.openSession();
        Transaction tx = session.beginTransaction();
        Student student = new Student();
        student.setName(&quot;chandrashekhar&quot;);
        student.setRollNumber(007);
        session.save(student);
        tx.commit();
        session.close();
        
    }
}

Output:

INFO: Envers integration enabled? : true
Hibernate: select max(id) from student
Hibernate: insert into onlinetutorialspoint.student (name, rollnumber, id) values (?, ?, ?)

By observing the above out put, hibernate first get the max(id) from the database and after executed the insert command.

sequence generator :

sequence is a shortcut name for SequenceGenerator class. It reads next value of a database sequence and then returns that value as id to the hibernate.

To use this sequence generator, In hibernate configuration file (hbm.xml) we need to configure the database sequence name as a parameter to the SequenceGenertor class.

If we don’t configure a database sequence name as a parameter, then SequenceGenerator class creates its own sequence with the name hibernate_sequence. After that, it reads the next value of that sequence.

We can create a sequence in database by using below syntax :


create sequence <sequence name> start with <Number> increment by <Number>;

If we create a sequence in database then we can set behavior like starting value and increment value. If SequenceGenerator class created by its own sequence called hibernate_sequence then it will set the default behavior as start with 1 and increment by 1.

Example :


<id name="studentId" column="sid">
            <generator class="sequence">
                <param name="sequence">mysequence</param>
            </generator>
</id>

Or

<id name="studentId" column="sid">
            <generator class="sequence"/>
</id>

In the first syntax, we are passing “mysequence” as name of the sequence. So we need to create a sequence in database like the following :


SQL> create sequence mysequence start with 10 increment by 5;

In syantax2 sequence name is not mentioned. So Generator class creates its own sequence with the name of  hibernate_sequence.

Sequence is a Database dependent of generated class. For example the sequence generator can be used in Oracle database, but it can not be used in mySQL Database.

hilo generator :

hilo is a shortcut name for TableHiloGenerator class. It is some thing different compared to other generator classes. Let us see how it is differ with others.

When we configure hilo generator class in hbm.xml file, along with the generator name we can pass 3 parameters :

  1. table
  2. column
  3. max_lo

Syntax :


<id name="studentId" column="sid">
            <generator class="hilo">
                <param name="table">mytable</param>
                <param name="column">col1</param>
                <param name="max_lo">10</param>
            </generator>
</id>

If we do not configure the above 3 parameters then hibernate will give the default values to them as :

  • table : hibernate_unique_key
  • column : next_hi
  • max_lo : 32767

hilo  generator follows a formula to generate Id. It always generates first id as “1”.

From the next Id onwards it will apply a formula for generating Id.

Hilo generator formula :

max_lo * next_hi +next_hi

By taking the given parameters, hilo will create a table with one column and calculate the column value based on the hilo formula.

Case Study :

Let us calculate the Id value for bellow parameters :

<id name=”id” column=”id” type=”java.lang.Integer”>
<generator class=”hilo”>
<param name=”table”>mytable </param>
<param name=”column”>col1 </param>
<param name=”max_lo”>10 </param>
</generator>
</id>

Here we took table name as mytable , column name as col1 and max_lo value is 10.

  • When first time hilo generator executed then id is ‘1’.
  • Second time onwards hilo uses formula for generating the Id. So by applying the above formula the Id is “11”

               max_lo * next_hi + next_hi

here,  max_lo = 10 (in hbm.xml we configured)

next_hi = 1 (already existed value in the column col1)

then

               10 * 1 + 1 = 11 and in the col1 it updates the value as “2” (Phase 2)

  • For third time hilo generates id as “22”

               10 * 2 + 2 = 22 and in the col1 it updates the value as “3”  (Phase 3)

This is how hilo generator works. And hilo generator is database independent generator, It will work on all databases.

identity generator :

identity is a shortcut name for IdentityGenerator class. It is a database dependent generator i.e. it will work on some databases only, example it works on MySql not in Oracle database.


<id name="studentId" column="sid">
            <generator class="identity"/>
</id>

When IdentityGenerator class calls, it reads an auto incremented column algorithm of database and take the auto incremented value and returns it as id to hibernate.

But Auto incremented algorithm doesn’t exist in all databases, hence identity generator is a database dependent generator.

For example : identity generator works on mySQL database but doesn’t works on Oracle database because there is no autoincrement functionality in Oracle database.

native generator :

If we configure the generator as native, this behavior is vary from database to database.


<id name="studentId" column="sid">
            <generator class="native"/>
</id>

The native generator will first checks for, is the database supports identity generator or not.

If the database supports identity generator then it acts as identity. If the database doesn’t supports for identity, it will checks for sequence generator.

If the database supports for sequence generator, then it acts as sequence. Or if the database doesn’t supports for sequence, It will checks for hilo generator.

Since the hilo generator is database independent, then there is no chance to hilo doesn’t acts as native generator. At least native generator should acts as hilo generator.

foreign generator :

foreign is a  shortcut name for ForeignGenerator class. The ForeignGenerator is only applicable for one-one relation ship.


<id name="studentId" column="sid">
            <generator class="foreign"/>
</id>

The ForeignGenerator class returns id of parent object as id for child object.

uuid generator :

Except assigned generator, remaining all generator classes discussed above will work for number type of primary key.

If a primary key of a table is string type then we can use assign generator or we can use another generator class uuid (Universal Unique Identifier) generator.


<id name="studentId" column="sid">
            <generator class="uuid"/>
</id>

uuid is a shortcut for AbstractUUIDGenerator class. uuid generator generates a string of 32 characters length based on the following 4 values:

  1. IP Address of the machine
  2. Start up time of JVM
  3. System time
  4. Counter value in JVM

Based on the four values UUIDGenerator class generates an unique Identifier and returns to hibernate.

Though it is system generated or unique identifier, there is a problem with using this uuid generator. To load an object from the database we can use either get() or load() methods in hibernate. To load an object we need to pass parameters to get() or load() methods as :

get(Class class,Serializable id);

load(Class class,Serializable id);

To use above two methods, we need to pass the primary key value of the table to get the details from data base. If the primary key id is generated by uuid generator, it will generate a string with 32 characters. As this is too long, it is not recommended to use. For this we can go with custom generator classes.

 

About chandrashekhar

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+ ,

Recommended

Hibernate Native SQL Query Example

In this tutorials, we are going to learn about Hibernate Native SQL with example. Hibernate …

Leave a Reply

Your email address will not be published. Required fields are marked *