Creating a SessionFactory in Hibernate 4

I’m working on the first major chapter of the Hibernate course for VirtualPairProgrammers and I’m working through the process of writing our first object to the database.

I’ve been using Hibernate for years, so I’m well used to the process of creating the SessionFactory, but in Hibernate 4 they’ve changed the process around – but the documentation on what to do is terrible. (Nb – this is at the time of writing, it may have improved by the time you read this).

Essentially, the buildSessionFactory() method on the Configuration class has been deprecated.

Instead, you have to pass in a “ServiceRegistry” into the buildSessionFactory method. The reasons for this aren’t clear to me (I can’t find any documentation explaining why, so if you know please tell me and I’ll give you a credit on the course!)

After a few attempts, my code kept crashing with the following warning:

WARN: HHH000181: No appropriate connection provider encountered, assuming application will be supplying connections

Which I think means “unable to get a connection”

The exception given was:

Exception in thread "main" org.hibernate.HibernateException: Connection cannot be null when 'hibernate.dialect' not set

This is a terrible error because it implies I haven’t set the Hibernate Dialect (the dialect is essentially the name of the database vendor). Actually, Hibernate will automatically work out the database dialect, but it needs a connection to the database to do this. So the error thrown is a symptom of the problem, rather than the problem itself.

Anyway, I got it working in the end, here’s the code I’ve used on the course:

private static SessionFactory sessionFactory;

public static SessionFactory getSessionFactory()
{
   if (sessionFactory == null)
   {
      Configuration configuration = new Configuration();

      ServiceRegistry serviceRegistry = new
         ServiceRegistryBuilder().applySettings
                  (configuration.configure().getProperties()).buildServiceRegistry();

      sessionFactory = configuration.buildSessionFactory(serviceRegistry);
   }
   return sessionFactory;
}

This will be in some kind of helper class.

I must admit that I’ve struggled to get this first chapter done as I’ve found it hard to pick my way through all the steps needed to get to your first running Hibernate application. Hopefully I’ll speed up now we’re up and running – progress will be reported on the blog.