天天看點

HibernateUtil

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;

 }

}