Java tutorial
/* * Copyright (c) 2009 - 2010. School of Information Technology and Electrical * Engineering, The University of Queensland. This software is being developed * for the "Phenomics Ontoogy Driven Data Management Project (PODD)" project. * PODD is a National e-Research Architecture Taskforce (NeAT) project * co-funded by ANDS and ARCS. * * PODD is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * PODD is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with PODD. If not, see <http://www.gnu.org/licenses/>. */ package podd.util.db.impl; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.cfg.Configuration; import org.hibernate.cfg.Environment; import org.springframework.beans.factory.DisposableBean; import podd.util.db.HibernateSessionFactory; /** * @author Yuan-Fang Li * @version $Id$ */ public class HibernateSessionFactoryImpl implements HibernateSessionFactory, DisposableBean { private static final Logger LOG = LoggerFactory.getLogger(HibernateSessionFactoryImpl.class); private SessionFactory factory; private ThreadLocal<Session> map; public HibernateSessionFactoryImpl(String configurationFileURL) { map = new ThreadLocal<Session>(); LOG.debug("HibernateSessionFactoryUtil.static - loading config"); final Configuration configuration = new Configuration().setProperties(Environment.getProperties()); factory = configuration.configure(configurationFileURL).buildSessionFactory(); LOG.debug("HibernateSessionFactoryUtil.static - end"); } @Override public synchronized Session currentSession() { Session session = map.get(); if (null == session) { session = factory.openSession(); map.set(session); } return session; } @Override public synchronized void closeSession() { Session session = map.get(); map.set(null); if (session != null) { //SessionFactoryUtils.releaseSession(session, factory); session.close(); } } @Override public void destroy() throws Exception { factory.close(); } public SessionFactory getSessionFactory() { return factory; } }