There are occasional wow moments in technology and I had one such moment in the summer of 2004 when I joined a project that was using Hibernate. In a matter of hours I was reading and writing beans and it was so effortless it seemed like magic.
Today I decided to take a look at Hibernate 4.1 and for several hours I have not been saying wow but why? and what? and worse…
Starting a Hibernate project used to be easy. The first test went something like this:
Properties properties = new Properties(); properties.setProperty(Environment.DIALECT, "org.hibernate.dialect.HSQLDialect"); properties.setProperty(Environment.URL, "jdbc:hsqldb:mem:test"); properties.setProperty(Environment.DRIVER, "org.hsqldb.jdbcDriver"); properties.setProperty(Environment.USER, "sa"); Configuration configuration = new Configuration() .setProperties(properties) .addClass(FeedTradePersistable.class); SessionFactory sessionFactory = configuration.buildSessionFactory();
buildSessionFactory() is deprecated, and yet in the user guide, section 3.2 Obtaining a SessionFactory, the code sample is still:
SessionFactory sessions = cfg.buildSessionFactory();
I am not impressed. The Javadoc says use
buildSessionFactory(ServiceRegistry) instead. But where is the code? The simple few lines to cut and paste to get me started?
I turn to Google. There are a few StackTrace questions on the subject and a Hibernate forum post that no Hibernate team member has responded to – BUT I CAN FIND NO OFFICIAL EXAMPLE! I’m beginning to think this is quite bad. The latest release of one of the most popular and depended on frameworks and it hinges on a deprecated method!
I spend a frustrating hour going round various Hibernate 4 presentations and blogs. I try something with
MetadataSources but fail. More Googling and it appears this work isn’t finished yet and shouldn’t be used – however there is no comment to this affect in the JavaDoc!
I look at the unit tests and find
BaseCoreFunctionalTestCase, it creates Sessions but it’s not exactly a simple example.
Eventually I go with what I found on StackOverflow:
ServiceRegistryBuilder serviceRegistryBuilder = new ServiceRegistryBuilder(); serviceRegistryBuilder.applySettings(properties); ServiceRegistry serviceRegistry = serviceRegistryBuilder.buildServiceRegistry(); Configuration configuration = new Configuration() .addClass(FeedTradePersistable.class); SessionFactory sessionFactory = configuration.buildSessionFactory(serviceRegistry);
It works, but is it best practice?
I feel a bit sad as I write this, I’ve lost my feel good about Hibernate feeling, and I think others will too. All I can say is, Hibernate – please don’t deprecate yourself.