import java.lang.ref.* import org.hibernate.* /** * This class is, strictly speaking, an internal implementation detail * of HibernatePlugin.cfc. However, it is designed to be used by * external Groovy scripts and therefore has a stable API. If you're * going to use it directly, you MUST call setPageContext(pageContext) * or HibernatePlugin.initializeRequest before invoking the session * methods. */ class SessionFactoryWrapper { private static final String REQUEST_SESSION_KEY = "__cfgroovy_hibernate_sessionfactorywrapper_session__" private static final ThreadLocal requestContext = new ThreadLocal() SessionFactory sessionFactory private String sessionKey def SessionFactoryWrapper(sessionFactory, engineId) { this.sessionFactory = sessionFactory this.sessionKey = REQUEST_SESSION_KEY + engineId } def setPageContext(pageContext) { // use a WeakReference so the request can be garbage collected SessionFactoryWrapper.requestContext.set(new WeakReference(pageContext.request)) } private Object getRequest() { def request = requestContext.get()?.get() if (! request) { throw new NoPageContextException() } request } def openSession() { closeSession() getCurrentSession() } def getCurrentSession() { def request = getRequest() if (request.getAttribute(sessionKey) == null) { request.setAttribute(sessionKey, sessionFactory.openSession()) } request.getAttribute(sessionKey) } def closeSession() { def request = getRequest() if (request.getAttribute(sessionKey) != null) { request.getAttribute(sessionKey).close() request.removeAttribute(sessionKey) } } @Deprecated def getSessionForRequest(pageContext) { setPageContext(pageContext) getCurrentSession() } @Deprecated def closeRequest(pageContext) { setPageContext(pageContext) closeSession() } def close() { sessionFactory.close() sessionFactory = null } } class NoPageContextException extends IllegalStateException { def NoPageContextException() { super("SessionFactoryWrapper requires a page context to operate on; you must call setPageContext before invoking other methods.") } }