Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hibernate 4.3.0.Final get session

In the hibernate documentation for version 4.3.0.Final the following code snippet is given to create a SessionFactory:

package org.hibernate.tutorial.util;

import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

public class HibernateUtil {

    private static final SessionFactory sessionFactory = buildSessionFactory();

    private static SessionFactory buildSessionFactory() {
        try {
            // Create the SessionFactory from hibernate.cfg.xml
            return new Configuration().configure().buildSessionFactory();
        }
        catch (Throwable ex) {
            // Make sure you log the exception, as it might be swallowed
            System.err.println("Initial SessionFactory creation failed." + ex);
            throw new ExceptionInInitializerError(ex);
        }
    }

    public static SessionFactory getSessionFactory() {
        return sessionFactory;
    }

}

This seems to be outdated, as the method buildSessionFactory() is deprecated. What is the correct way to create the SessionFactory?

like image 200
jzwiener Avatar asked Jan 01 '14 15:01

jzwiener


1 Answers

public class TestHB4 {
    private static StandardServiceRegistry serviceRegistry;
    private static SessionFactory sessionFactory;

    public static void main(String[] args) {
        Person person = new Person();
        person.setFirstName("Namal");
        person.setLastName("Dinesh");


        Configuration configuration = new Configuration().configure();
        serviceRegistry = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties()).build();
        sessionFactory = configuration.configure().buildSessionFactory(serviceRegistry);

        Session session = sessionFactory.openSession();

        session.beginTransaction();

        session.save(person);

        session.getTransaction().commit();
        session.close();


    }
like image 123
Namal Dinesh Ubhayawardana Avatar answered Oct 02 '22 06:10

Namal Dinesh Ubhayawardana