Newer
Older
CosmosServer / src / test / java / hibernateTest / models / SessionFactoryManager.java
package hibernateTest.models;

import org.hibernate.SessionFactory;
import org.hibernate.boot.MetadataSources;
import org.hibernate.boot.registry.StandardServiceRegistry;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;

import javax.inject.Singleton;


@Singleton
public class SessionFactoryManager {
    private static SessionFactoryManager theInstance = null;
    private static SessionFactory sessionFactory;

    private SessionFactoryManager(){
        setUp();
    }

    public static SessionFactoryManager getInstance(){
        if(theInstance == null){
            theInstance = new SessionFactoryManager();
        }
        return theInstance;
    }

    public static void setUp() {
        // A SessionFactory is set up once for an application!
        final StandardServiceRegistry registry = new StandardServiceRegistryBuilder()
                .configure() // configures settings from hibernate.cfg.xml
                .build();
        try {
            sessionFactory = new MetadataSources( registry ).buildMetadata().buildSessionFactory();
        }
        catch (Exception e) {
            // The registry would be destroyed by the SessionFactory, but we had trouble building the SessionFactory
            // so destroy it manually.
            StandardServiceRegistryBuilder.destroy( registry );
        }
    }

    public static void tearDown() {
        try {
            if ( sessionFactory != null ) {
                sessionFactory.close();
            }
        } catch (Exception e) {
            System.out.println("Exception!");
        }
    }

    public static SessionFactory getSessionFactory(){
        return sessionFactory;
    }

}