/************************************************
 * Copyright (c) Shen Li. All rights reserved.  *
 * http://joyaop.sourceforge.net                *
 * -------------------------------------------- *
 * Distributable under LGPL license.            *
 * See terms of license at gnu.org.             *
 ************************************************/
package net.sf.joyaop.demo.rbac;

import net.sf.joyaop.ObjectFactory;
import net.sf.joyaop.extension.hibernate.JoyInterceptor;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Interceptor;
import org.hibernate.cfg.Configuration;
import org.hibernate.tool.hbm2ddl.SchemaExport;

/**
 * @author Shen Li
 */
public class SessionManager {
    private final ThreadLocal sessionHolder = new ThreadLocal();
    private final SessionFactory sessionFactory;

    public SessionManager(ObjectFactory objectFactory) {
        Configuration configuration = new Configuration().configure();
        Interceptor interceptor = new JoyInterceptor(objectFactory, configuration);
        configuration.setInterceptor(interceptor);
        new SchemaExport(configuration).create(true, true);
        sessionFactory = configuration.buildSessionFactory();
    }

    public Session getSession() {
        Session session = (Session) sessionHolder.get();
        if (session == null) {
            throw new RuntimeException("Session not found.");
        }
        return session;
    }

    public Session openSession() {
        Session session;
        session = sessionFactory.openSession();
        sessionHolder.set(session);
        return session;
    }

    public void closeSession() {
        Session session = getSession();
        sessionHolder.set(null);
        if (session != null) {
            session.close();
        }
    }
}
