Session factory for Hibernate 4 using buildSessionFactory and ServiceRegistry

Your ads will be inserted here by

Easy Plugin for AdSense.

Please go to the plugin admin page to
Paste your ad code OR
Suppress this ad slot.

In Hibernate 3:

private static SessionFactory factory;
Configuration config = HibernateUtil.getInitializedConfiguration();
factory = config.buildSessionFactory();
Session session = factory.getCurrentSession();

In Hibernate 4:
You need to pass a ServiceRegistry class to buildSessionFactory:

Configuration config = new Configuration().configure("hibernate.cfg.xml");
config.addAnnotatedClass(DatastreamTriggers.class); //your JPA models
config.addAnnotatedClass(Follower.class);//your JPA models
config.addAnnotatedClass(Subject.class);//your JPA models
serviceRegistry = new ServiceRegistryBuilder().applySettings(config.getProperties()).buildServiceRegistry();
factory = config.buildSessionFactory(serviceRegistry);
Session session = factory.getCurrentSession();

Using metadatasources:

ServiceRegistry serviceRegistry = new ServiceRegistryBuilder().configure().buildServiceRegistry();
MetadataSources metadataSources = new MetadataSources(serviceRegistry);
SessionFactory sessionFactory = metadataSources.buildMetadata().buildSessionFactory();

One thought on “Session factory for Hibernate 4 using buildSessionFactory and ServiceRegistry

Leave a Reply

Your email address will not be published. Required fields are marked *