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.
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 result