com.mtech.easyexchange.SessionFactoryProvider.java Source code

Java tutorial

Introduction

Here is the source code for com.mtech.easyexchange.SessionFactoryProvider.java

Source

/*
 * This file is part of EasyExchange.
 *
 * (c) 2014 - Machiel Molenaar <machiel@machiel.me>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

package com.mtech.easyexchange;

import org.hibernate.FlushMode;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.boot.registry.StandardServiceRegistry;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
import org.hibernate.context.internal.ManagedSessionContext;

public class SessionFactoryProvider {

    protected static final SessionFactory sessionFactory = createSessionFactory();

    protected static SessionFactory createSessionFactory() {
        try {

            Configuration cfg = new Configuration();
            cfg.configure("hibernate.cfg.xml");

            StandardServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder()
                    .applySettings(cfg.getProperties()).build();
            return cfg.buildSessionFactory(serviceRegistry);

        } catch (Throwable ex) {
            System.err.println("Initial SessionFactory Creation Failed");
            throw new ExceptionInInitializerError(ex);
        }
    }

    public static SessionFactory getSessionFactory() {
        return sessionFactory;
    }

    public static Session openSession() {
        Session session = sessionFactory.openSession();
        session.setFlushMode(FlushMode.MANUAL);

        ManagedSessionContext.bind(session);

        return session;
    }

    public static Session getCurrentSession() {
        return sessionFactory.getCurrentSession();
    }

    public static void close() {
        sessionFactory.close();
    }

}