package com.huxin.patternenemia.tools;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
/*
* @author:hu_xinxin的专栏
*/
public class HibernateUtil {
private static SessionFactory factory;
private static ThreadLocal<Session> threadSession = new ThreadLocal<Session>();
private static ThreadLocal<Transaction> threadTransaction = new ThreadLocal<Transaction>();
//读取配置文件,所以只需要加载一次,使用静态代码块
static{
Configuration cfg = new Configuration().configure();
factory = cfg.buildSessionFactory();
}
public static SessionFactory getFactory(){
return factory;
}
public static Session getSession(){
Session session = threadSession.get();
if(session == null){
session = factory.openSession();
threadSession.set(session);
}
return session;
}
public static void close(){
Session session = threadSession.get();
if(session == null){
if(session.isOpen()){
session.close();
threadSession.remove(); //一定要记得remove掉这个session的对象
}
}
}
//开启一个事务
public static Transaction getTransaction(){
Session session = threadSession.get();
Transaction transaction = threadTransaction.get();
if(transaction==null){
transaction = session.beginTransaction();
threadTransaction.set(transaction);
}
return transaction ;
}
//事务提交或者回滚,一定要删除这个事务
public static void commitTransaction(Transaction transaction){
transaction.commit();
removeTransaction();
}
public static void rollbackTransaction(Transaction transaction){
transaction.rollback();
removeTransaction();
}
public static void removeTransaction(){
threadTransaction.remove();
}
}
关于HibernateUtil的一个封装
最新推荐文章于 2018-04-17 00:18:25 发布