package com.huawei.ssh.entity;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
public class HibernateUtil {
private static Configuration configuration;
private static SessionFactory sessionFactory;
private static boolean useThreadLocal = true;
private static ThreadLocal threadSession = new ThreadLocal();
private static ThreadLocal threadTransaction = new ThreadLocal();
/**
* 获取配置文件
*/
static {
try {
// 创建Configuration对象
configuration = new Configuration();
// 读取hibernate.cfg.xml文件
configuration.configure();
sessionFactory = configuration.buildSessionFactory();
} catch (Exception e) {
System.out.println("init exception " + e);
}
}
/**
* @return SessionFactory
*/
public static SessionFactory getSessionFactory() {
return sessionFactory;
}
/**
* @return 获取当前session
*/
public static Session getCurrentSession() {
if (useThreadLocal) {
Session s = (Session) threadSession.get();
if (s == null) {
s = getSessionFactory().openSession();
threadSession.set(s);
}
return s;
} else {
return getSessionFactory().getCurrentSession();
}
}
/**
*关闭session对象
*/
public static void closeSession()
{
Session session = (Session)threadSession.get();
threadSession.set(null);
if(session!=null&&session.isOpen())
{
session.close();
}
}
/**
* 开始事务
*/
public static void beginTransaction()
{
Transaction tx = (Transaction)threadTransaction.get();
if(tx==null)
{
tx = getCurrentSession().beginTransaction();
threadTransaction.set(tx);
}
}
/**
* 提交事务
*/
public static void commitTransaction()
{
Transaction tx = (Transaction)threadTransaction.get();
try
{
if(tx!=null&&!tx.wasCommitted()&&!tx.wasRolledBack())
{
tx.commit();
}
threadTransaction.set(null);
}catch(Exception ex)
{
rollbackTransaction();
System.out.println("回滚 "+ex);
}
}
/**
* 回滚事务
*/
public static void rollbackTransaction()
{
Transaction tx = (Transaction)threadTransaction.get();
try
{
threadTransaction.set(null);
if(tx!=null&&!tx.wasCommitted()&&!tx.wasRolledBack())
{
tx.rollback();
}
}catch(Exception ex)
{
System.out.println("Rollback exception "+ex);
}finally
{
closeSession();
}
}
}