Increment with hibernate generator

This is continuation of my previous post.

We discussed with different type of generators for primary keys and we have seen an example with ‘assigned’ previously. We can see ‘generator‘ in this post.

RoseIndia says we shouldnt use this in clustered invironment.

Create a table using the following structure.

BOOK-table structure

BOOK-table structure

Let your DTO be like this

package hib;

public class Book {
 private long bookID;
 private String bookName;
 public long getBookID() {
 return bookID;
 public void setBookID(long bookID) {
 this.bookID = bookID;
 public String getBookName() {
 return bookName;
 public void setBookName(String bookName) {
 this.bookName = bookName;

Add the following entries to contact.hbm.xml inside the root element

<class name="hib.Book" table="BOOK">
 <id name="bookID" type="long" column="ID">
 <property name="bookName">
 <column name="BOOKNAME"></column>

Let your client program be as follows

package hib;

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;

public class IncrementTest {

 * @param args
 public static void main(String[] args) {
 Session session=null;
 try {
 SessionFactory sessionFactory=new Configuration().configure().buildSessionFactory();
 session = sessionFactory.openSession();
 Transaction tx = session.beginTransaction();
 System.out.println("Transaction beginning");
 Book book = new Book();
 book.setBookName("LIVE LA FRANCE");;
 System.out.println("book stored");
 } catch (HibernateException e) {
 if (session!=null){

And be happy, your inserted the records with auto incrementing ID 🙂

book console

book console

book result

book result

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s