Monday, June 25, 2012

How to Create Session Factory in Hibernate 4

You've probably noticed that org.hibernate.cfg.Configuration.buildSessionFactory is deprecated in Hibernate4, check out Javadocs:

/**
 * Create a {@link SessionFactory} using the properties and mappings in this configuration. The
 * {@link SessionFactory} will be immutable, so changes made to {@code this} {@link Configuration} after
 * building the {@link SessionFactory} will not affect it.
 *
 * @return The build {@link SessionFactory}
 *
 * @throws HibernateException usually indicates an invalid configuration or invalid mapping information
 *
 * @deprecated Use {@link #buildSessionFactory(ServiceRegistry)} instead
 */
public SessionFactory buildSessionFactory() throws HibernateException 

E.g. We have the next old-fashion Hibernate3 code snippets:
SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();

Session session = sessionFactory.openSession();
session.beginTransaction();
session.save(new Event("Our very first event!", new Date()));
session.save(new Event("A follow up event", new Date()));
session.getTransaction().commit();
session.close();

Based on Javadocs above we have to apply the next small changes to support new Hibernate 4 buildSessionFactory(ServiceRegistry):
Configuration configuration = new Configuration();
configuration.configure();
ServiceRegistry serviceRegistry = new ServiceRegistryBuilder().applySettings(configuration.getProperties()).buildServiceRegistry();
SessionFactory sessionFactory = configuration.buildSessionFactory(serviceRegistry);

Session session = sessionFactory.openSession();
session.beginTransaction();
session.save(new Event("Our very first event!", new Date()));
session.save(new Event("A follow up event", new Date()));
session.getTransaction().commit();
session.close();
You can clone code sample from https://github.com/halyph/tutorials/tree/master/hibernate4-session-factory-sample