import net.sf.hibernate.HibernateException;
import net.sf.hibernate.Session;
import net.sf.hibernate.SessionFactory;
import net.sf.hibernate.Transaction;
import net.sf.hibernate.cfg.Configuration;
public class HibernateUtil {
private static SessionFactory sessionFactory;
//private static Log log = LogFactory.getLog(HibernateUtil.class);
static{
try{
//创建SessionFactory
sessionFactory = new Configuration().configure()
.buildSessionFactory();
}catch(Throwable ex){
ex.printStackTrace();
System.out.println();
}
}
public static final ThreadLocal tLocalsess = new ThreadLocal();
public static final ThreadLocal tLocaltx = new ThreadLocal();
//取得Session
public static Session currentSession(){
Session session = (Session)tLocalsess.get();
//如果当前的不可用,打开一个新的session
try{
if(session == null || !session.isOpen()){
session = sessionFactory.openSession();
tLocalsess.set(session);
}
}catch(Exception e){
e.printStackTrace();
}
return session;
}
//关闭Session
public static void closeSession(){
Session session = (Session)tLocalsess.get();
tLocalsess.set(null);
try{
if(session != null && session.isOpen()){
session.close();
}
}catch(HibernateException e){
e.printStackTrace();
}
}
//开始事务
public static void beginTransaction(){
//声明Transaction类型对象tx,并赋初值
Transaction tx = (Transaction)tLocaltx.get();
try{
if(tx == null){
tx = currentSession().beginTransaction();
tLocaltx.set(tx);
}
}catch(HibernateException e){
e.printStackTrace();
}
}
//关闭事务
public static void commitTransaction(){
Transaction tx = (Transaction)tLocaltx.get();
try{
if(tx != null && !tx.wasCommitted() && !tx.wasRolledBack()){
tx.commit();
}
tLocaltx.set(null);
System.out.println("commit tx");
}catch(HibernateException e){
e.printStackTrace();
}
}
//事务回滚
public static void roollbackTransaction(){
Transaction tx = (Transaction)tLocaltx.get();
try{
tLocaltx.set(null);
if(tx != null && !tx.wasCommitted() && !tx.wasRolledBack()){
tx.rollback();
}
}catch(HibernateException e){
e.printStackTrace();
}
}
private static Session openSession() throws HibernateException{
return getSessionFactory().openSession();
}
private static SessionFactory getSessionFactory() throws HibernateException{
return sessionFactory;
}
}