Newer
Older
CosmosServer / src / main / java / com / example / cosmos_serversb / models / SessionManager.java
package com.example.cosmos_serversb.models;

import org.hibernate.Session;
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 SessionManager {
    private static SessionManager theInstance = null;
    private static SessionFactory sessionFactory;
    private static Session session = null;

    private SessionManager(){
        setUp();
    }

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

    public static Session getSession(){
        if(session == null){
            session = sessionFactory.openSession();
            session.beginTransaction();
        }
        return session;
    }

    public static void closeSession(){
        if(session != null) {
            session.getTransaction().commit();
            session.close();
            session = null;
        }
    }

    public static SessionFactory getSessionFactory(){
        return sessionFactory;
    }


    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!");
        }
    }

}