package com.app.www.hibernate; import java.sql.SQLException; import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration; public class HibernateSessionFactory
{
private static final ThreadLocal<Session> threadLocal = new ThreadLocal<Session>();
private static Configuration configuration = new Configuration().configure();
private static SessionFactory sessionFactory; /**
* 私有化构造
*/
private HibernateSessionFactory()
{
} /**
* 创建SessionFactory
*/
public static void rebulidSessionFactory()
{
sessionFactory = configuration.buildSessionFactory();
} /**
* 获取SessionFactory
* @return SessionFactory
*/
public static SessionFactory getSessionFactory()
{
if(sessionFactory == null)
{
rebulidSessionFactory();
}
return sessionFactory;
} /**
* 获取Session
* @return Session
*/
public static Session getCurrentSession()
{
Session session = threadLocal.get();
try
{
if (session == null || !session.isOpen() || session.connection().isClosed())
{
if (sessionFactory == null)
{
rebulidSessionFactory();
}
session = (sessionFactory == null) ? null : sessionFactory.getCurrentSession();
threadLocal.set(session);
}
} catch (HibernateException e)
{
e.printStackTrace();
} catch (SQLException e)
{
e.printStackTrace();
}
return session;
} /**
* 关闭Session
*/
public static void closeCurrentSession()
{
Session session = threadLocal.get();
threadLocal.set(null); if (session != null)
{
session.close();
}
} /**
* 获取 Configuration
* @return Configuration
*/
public static Configuration getConfiguration()
{
return configuration;
}
}