Monday, May 09, 2005

Hibernate in Action

I have been trying to learn to use Hibernate over the last couple of days. After reading through the first 2 chapters in Hibernate In Action, I decided to try the "Message" example mentioned in the book. I used HSQLDB to persist the data. Initially I thought that we only needed to add the jdbc driver (i.e hsqldb.jar) and hibernate3.jar in the classpath. But then, a whole series of exceptions hit me in the face one after the other. Reading through the stack trace and resolving the exceptions one by one, I finally figured that the following jars need to be in the classpath for the program to run successfully.
  • the jdbc driver (in my case hsqldb.jar)
  • hibernate3.jar
  • asm.jar
  • cglib-2.1.jar
  • commons-collections-2.1.1.jar
  • commons-logging-1.0.4.jar
  • log4j-1.2.9.jar
  • jta.jar
  • ehcache-1.1.jar
  • dom4j-1.6.jar
All of these jars (except for the jdbc driver) come bundled with hibernate 3.0.

While specifying the configuration options for hibernate, we have 2 options --- either to use the hibernate.properties file or the hibernate.cfg.xml. There are subtle differences b/w these 2 methods :-

1) If you are using the hibernate.properties file --- While building the SessionFactory object, we don't need to call Configuration.configure() , but we do need to call Configuration.addResource() to specify the mapping files. i.e. --
Configuration configuration = new Configuration();
configuration.addResource("Messages/Message.hbm.xml");
SessionFactory sessionFactory = configuration.buildSessionFactory();

If you are using the C3P0 connection pool, you need to add c3p0-0.8.5.2.jar (comes with hibernate 3.0) to the classpath.

2) If you are using the hibernate.cfg.xml file --- While building the SessionFactory object, we do need to call Configuration.configure() , but we don't need to call Configuration.addResource() to specify the mapping files since we could specify it in hibernate.cfg.xml itself. i.e. --
Configuration configuration = new Configuration();
SessionFactory sessionFactory = configuration.configure().buildSessionFactory();

Hope this helps when you are writing your first hibernate program :-)

5 comments:

ROhan Kini said...

Ha !!.. Looks like u didnt manage to get that program up and runnin that nite.

Post shows that u posted at 8:45 AM !!! .. Hehe ..

Anirudh said...

what exactly is Hibernate? from your post i got a feeling it is some mechanism of object persistence in java. Is that right? where are the objects stored? in any database? or in a file? why is it called Hibernate? why are you so ugly?

Chirdeep Shetty said...

All your questions (except for the last one) answered at www.hibernate.org

Diego Pires Plentz said...

Consider to read the new edition of the book
Java Persistence with Hibernate. ;)

Anil said...

that did help.. Thanks a bunch !