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">
 <generator></generator>
 </id>
 <property name="bookName">
 <column name="BOOKNAME"></column>
 </property>
 </class>

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");
 session.save(book);
 System.out.println("book stored");
 tx.commit();
 } catch (HibernateException e) {
 e.printStackTrace();
 }finally
 {
 if (session!=null){
 session.flush();
 session.close();
 }
 }
 }
}

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

book console

book console

book result

book result

Advertisements

Leave a Reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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 )

Google+ photo

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

Connecting to %s