Friday, April 11, 2008

Playing with Hibernate.

So recently I'm in love in JAVA (at least my girlfriend says that). I'm developing simple project for my company (because I'm bored). Swing based thing with Hibernate and mssql.
I've used annotations to map classes to db, very cool thingy. Gotta love that. Everything in one file, class and database mapping. Some genius invented this :D But lets get to the point.

Following the manual on hibernate page good thing to do is to create a HibernateUtil (or call it whatever) class to help us menage hibernate session. (http://www.hibernate.org/hib_docs/v3/reference/en/html/tutorial.html#tutorial-firstapp) So I've created it. But I don't wanna use mapping files in xml's, I wanna use Annotations, so what I need to change is

sessionFactory = new Configuration().configure().buildSessionFactory();
to
sessionFactory = new AnnotationConfiguration().buildSessionFactory();

Hibernate has couple of configuration methods.
- You can configure thru the code, eg.
sessionFactory = new AnnotationConfiguration()
.addPackage("test.animals") //the fully qualified package name
.addAnnotatedClass(Flight.class)
.buildSessionFactory()

- Configure thru hibernate.properties file. Altrought that method (as far as i know) cannot directly add/configure annotated classes.

- And the last but best method thru hibernate.cfg.xml file. It is the common way of using hibernate.cfg.xml for Hibernate configuration.
File is very flexible, and understandable.

All tutorials and manuals on hibernate.org tell that hibernate.cfg.xml is the best way of configuring hibernate.
But, they don't tell that if you'll be using AnnotationConfiguration that file ISN'T searched in classpath!

That gave me smth. to think about when i was wondering why my configuration file isn't parsed. I've tryied adding in do different folders, debugging my app and nothing.
Then I've came up with simple idea. I simply put path to my config file in creation of sessionFactory. So it looks like this.

sessionFactory =
new AnnotationConfiguration()
.configure("/hibernate.cfg.xml")
.buildSessionFactory();

And boom~! Everything works fine ;-)