HibernateUtil.java

HibernateUtil.java
package com.my.webproject.persistence;
//import java.util.Properties;

import net.sf.hibernate.HibernateException;
import net.sf.hibernate.Interceptor;
import net.sf.hibernate.Session;
import net.sf.hibernate.SessionFactory;
import net.sf.hibernate.Transaction;
import net.sf.hibernate.cfg.Configuration;
//import net.sf.hibernate.cfg.Environment;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.my.webproject.exceptions.InfrastructureException;

/**
*
* Basic Hibernate helper class, handles SessionFactory, Session and Transaction.
*


*
* @author christian@hibernate.org
*/
   public class HibernateUtil {
   
   
private static Log log = LogFactory.getLog(HibernateUtil.class);
   
   
private static Configuration configuration;
   
private static SessionFactory sessionFactory;
   
private static final ThreadLocal threadSession = new ThreadLocal();
   
private static final ThreadLocal threadTransaction = new ThreadLocal();
   
private static final ThreadLocal threadInterceptor = new ThreadLocal();
   
   
// 根据默认的配置文件初始化SessionFactory
      static {
         
try {
         configuration =
new Configuration();
         
//hibernate.properties
         // Properties copy = new Properties();
         // copy.load(Environment.class.getResourceAsStream("/hibernate.properties"));
         // configuration.setProperties(copy);
         // configuration.addClass(org.hibernate.w3c.Employee.class);
         // configuration.addClass(org.hibernate.w3c.City.class);
         // configuration.addClass(org.hibernate.w3c.SupportDoc.class);
         // sessionFactory = configuration.buildSessionFactory();
          //hivernate.cfg.xml
         sessionFactory = configuration.configure().buildSessionFactory();
         
         
// We could also let Hibernate bind it to JNDI:
          // configuration.configure().buildSessionFactory()
         } catch (Throwable ex) {
         
// We have to catch Throwable, otherwise we will miss
          // NoClassDefFoundError and other subclasses of Error
         log.error("Building SessionFactory failed.", ex);
         
throw new ExceptionInInitializerError(ex);
      }
   }
   
   
/*
    * Returns the SessionFactory used for this static class.
    *
    * @return SessionFactory
    */
      public static SessionFactory getSessionFactory() {
      
/* Instead of a static variable, use JNDI:
      SessionFactory sessions = null;
         
try {
         Context ctx =
new InitialContext();
         
String jndiName = "java:hibernate/HibernateFactory";
         sessions = (SessionFactory)ctx.lookup(jndiName);
         }
catch (NamingException ex) {
         
throw new InfrastructureException(ex);
      }
      
return sessions;
      
*/
      return sessionFactory;
   }
   
   
/*
    * Returns the original Hibernate configuration.
    *
    * @return Configuration
    */
      public static Configuration getConfiguration() {
      
return configuration;
   }
   
   
/*
    * 使用默认的配置重建 SessionFactory .
    */
    public static void rebuildSessionFactory()
      
throws InfrastructureException {
         synchronized(sessionFactory) {
            
try {
            sessionFactory = getConfiguration().buildSessionFactory();
            }
catch (Exception ex) {
            
throw new InfrastructureException(ex);
         }
      }
    }
   
   
/*
    * 使用给定的配置重建 SessionFactory .
    * @param cfg
    */
    public static void rebuildSessionFactory(Configuration cfg)
      
throws InfrastructureException {
         synchronized(sessionFactory) {
            
try {
            sessionFactory = cfg.buildSessionFactory();
            configuration = cfg;
            }
catch (Exception ex) {
            
throw new InfrastructureException(ex);
         }
      }
    }
   
   
/*
    * 从当前的活动线程中找回当前的session
    *


    * 如果当前线程中没有打开的session ,打开一个新的session放入当前的活动线程。
    * @return Session
    */
   public static Session getSession()
      
throws InfrastructureException {
      Session s = (Session) threadSession.get();
         
try {
            
if (s == null) {
            log.debug("Opening
new Session for this thread.");
               
if (getInterceptor() != null) {
               log.debug("Using interceptor: " + getInterceptor().getClass());
               s = getSessionFactory().openSession(getInterceptor());
               }
else {
               s = getSessionFactory().openSession();
            }
            threadSession.set(s);
         }
         }
catch (HibernateException ex) {
         
throw new InfrastructureException(ex);
      }
      
return s;
   }
   
   
/*
    * 关闭当前活动线程中的session.
    */
   public static void closeSession()
      
throws InfrastructureException {
         
try {
         Session s = (Session) threadSession.get();
         threadSession.set(null);
            
if (s != null && s.isOpen()) {
            log.debug("Closing Session of this thread.");
            s.close();
         }
         }
catch (HibernateException ex) {
         
throw new InfrastructureException(ex);
      }
   }
   
   
/*
    * 开始一个新的数据库事务.
    */
   public static void beginTransaction()
      
throws InfrastructureException {
      Transaction tx = (Transaction) threadTransaction.get();
         
try {
            
if (tx == null) {
            log.debug("Starting
new database transaction in this thread.");
            tx = getSession().beginTransaction();
            threadTransaction.set(tx);
         }
         }
catch (HibernateException ex) {
         
throw new InfrastructureException(ex);
      }
   }
   
   
/*
    * 提交未决的数据库事务
    */
   public static void commitTransaction()
      
throws InfrastructureException {
      Transaction tx = (Transaction) threadTransaction.get();
         
try {
         
if ( tx != null && !tx.wasCommitted()
            && !tx.wasRolledBack() ) {
            log.debug("Committing database transaction of this thread.");
            tx.commit();
         }
         threadTransaction.set(null);
         }
catch (HibernateException ex) {
         rollbackTransaction();
         
throw new InfrastructureException(ex);
      }
   }
   
   
/*
    * 对数据库事务做回滚操作
    */
   public static void rollbackTransaction()
      
throws InfrastructureException {
      Transaction tx = (Transaction) threadTransaction.get();
         
try {
         threadTransaction.set(null);
            
if ( tx != null && !tx.wasCommitted() && !tx.wasRolledBack() ) {
            log.debug("Tyring to rollback database transaction of this thread.");
            tx.rollback();
         }
         }
catch (HibernateException ex) {
         
throw new InfrastructureException(ex);
         } finally {
         closeSession();
      }
   }
   
   
/*
    * 重新接合一个 Hibernate Session 到当前线程.
    * @param session The Hibernate Session to be reconnected.
    */
   public static void reconnect(Session session)
      
throws InfrastructureException {
         
try {
         session.reconnect();
         threadSession.set(session);
         }
catch (HibernateException ex) {
         
throw new InfrastructureException(ex);
      }
   }
   
   
/*
    * 从当前线程分离并返回一个Hibernate Session.
    * Disconnect and return Session from current Thread.
    *
    * @return Session the disconnected Session
    */
   public static Session disconnectSession()
      
throws InfrastructureException {
      
      Session session = getSession();
         
try {
         threadSession.set(null);
         
if (session.isConnected() && session.isOpen())
         session.disconnect();
         }
catch (HibernateException ex) {
         
throw new InfrastructureException(ex);
      }
      
return session;
   }
   
   
/*
    * Register a Hibernate interceptor with the current thread.
    * 在当前线程中注册一个Hibernate拦截机
    *


    * Every Session opened is opened with this interceptor after
    * registration. Has no effect if the current Session of the
    * thread is already open, effective on next close()/getSession().
    */
      public static void registerInterceptor(Interceptor interceptor) {
      threadInterceptor.set(interceptor);
   }
   
      
private static Interceptor getInterceptor() {
      Interceptor interceptor =
      (Interceptor) threadInterceptor.get();
      
return interceptor;
   }
   
   
}


*
* @author christian@hibernate.org
*/
   public class HibernateUtil {
   
   
private static Log log = LogFactory.getLog(HibernateUtil.class);
   
   
private static Configuration configuration;
   
private static SessionFactory sessionFactory;
   
private static final ThreadLocal threadSession = new ThreadLocal();
   
private static final ThreadLocal threadTransaction = new ThreadLocal();
   
private static final ThreadLocal threadInterceptor = new ThreadLocal();
   
   
// 根据默认的配置文件初始化SessionFactory
      static {
         
try {
         configuration =
new Configuration();
         
//hibernate.properties
         // Properties copy = new Properties();
         // copy.load(Environment.class.getResourceAsStream("/hibernate.properties"));
         // configuration.setProperties(copy);
         // configuration.addClass(org.hibernate.w3c.Employee.class);
         // configuration.addClass(org.hibernate.w3c.City.class);
         // configuration.addClass(org.hibernate.w3c.SupportDoc.class);
         // sessionFactory = configuration.buildSessionFactory();
          //hivernate.cfg.xml
         sessionFactory = configuration.configure().buildSessionFactory();
         
         
// We could also let Hibernate bind it to JNDI:
          // configuration.configure().buildSessionFactory()
         } catch (Throwable ex) {
         
// We have to catch Throwable, otherwise we will miss
          // NoClassDefFoundError and other subclasses of Error
         log.error("Building SessionFactory failed.", ex);
         
throw new ExceptionInInitializerError(ex);
      }
   }
   
   
/*
    * Returns the SessionFactory used for this static class.
    *
    * @return SessionFactory
    */
      public static SessionFactory getSessionFactory() {
      
/* Instead of a static variable, use JNDI:
      SessionFactory sessions = null;
         
try {
         Context ctx =
new InitialContext();
         
String jndiName = "java:hibernate/HibernateFactory";
         sessions = (SessionFactory)ctx.lookup(jndiName);
         }
catch (NamingException ex) {
         
throw new InfrastructureException(ex);
      }
      
return sessions;
      
*/
      return sessionFactory;
   }
   
   
/*
    * Returns the original Hibernate configuration.
    *
    * @return Configuration
    */
      public static Configuration getConfiguration() {
      
return configuration;
   }
   
   
/*
    * 使用默认的配置重建 SessionFactory .
    */
    public static void rebuildSessionFactory()
      
throws InfrastructureException {
         synchronized(sessionFactory) {
            
try {
            sessionFactory = getConfiguration().buildSessionFactory();
            }
catch (Exception ex) {
            
throw new InfrastructureException(ex);
         }
      }
    }
   
   
/*
    * 使用给定的配置重建 SessionFactory .
    * @param cfg
    */
    public static void rebuildSessionFactory(Configuration cfg)
      
throws InfrastructureException {
         synchronized(sessionFactory) {
            
try {
            sessionFactory = cfg.buildSessionFactory();
            configuration = cfg;
            }
catch (Exception ex) {
            
throw new InfrastructureException(ex);
         }
      }
    }
   
   
/*
    * 从当前的活动线程中找回当前的session
    *


    * 如果当前线程中没有打开的session ,打开一个新的session放入当前的活动线程。
    * @return Session
    */
   public static Session getSession()
      
throws InfrastructureException {
      Session s = (Session) threadSession.get();
         
try {
            
if (s == null) {
            log.debug("Opening
new Session for this thread.");
               
if (getInterceptor() != null) {
               log.debug("Using interceptor: " + getInterceptor().getClass());
               s = getSessionFactory().openSession(getInterceptor());
               }
else {
               s = getSessionFactory().openSession();
            }
            threadSession.set(s);
         }
         }
catch (HibernateException ex) {
         
throw new InfrastructureException(ex);
      }
      
return s;
   }
   
   
/*
    * 关闭当前活动线程中的session.
    */
   public static void closeSession()
      
throws InfrastructureException {
         
try {
         Session s = (Session) threadSession.get();
         threadSession.set(null);
            
if (s != null && s.isOpen()) {
            log.debug("Closing Session of this thread.");
            s.close();
         }
         }
catch (HibernateException ex) {
         
throw new InfrastructureException(ex);
      }
   }
   
   
/*
    * 开始一个新的数据库事务.
    */
   public static void beginTransaction()
      
throws InfrastructureException {
      Transaction tx = (Transaction) threadTransaction.get();
         
try {
            
if (tx == null) {
            log.debug("Starting
new database transaction in this thread.");
            tx = getSession().beginTransaction();
            threadTransaction.set(tx);
         }
         }
catch (HibernateException ex) {
         
throw new InfrastructureException(ex);
      }
   }
   
   
/*
    * 提交未决的数据库事务
    */
   public static void commitTransaction()
      
throws InfrastructureException {
      Transaction tx = (Transaction) threadTransaction.get();
         
try {
         
if ( tx != null && !tx.wasCommitted()
            && !tx.wasRolledBack() ) {
            log.debug("Committing database transaction of this thread.");
            tx.commit();
         }
         threadTransaction.set(null);
         }
catch (HibernateException ex) {
         rollbackTransaction();
         
throw new InfrastructureException(ex);
      }
   }
   
   
/*
    * 对数据库事务做回滚操作
    */
   public static void rollbackTransaction()
      
throws InfrastructureException {
      Transaction tx = (Transaction) threadTransaction.get();
         
try {
         threadTransaction.set(null);
            
if ( tx != null && !tx.wasCommitted() && !tx.wasRolledBack() ) {
            log.debug("Tyring to rollback database transaction of this thread.");
            tx.rollback();
         }
         }
catch (HibernateException ex) {
         
throw new InfrastructureException(ex);
         } finally {
         closeSession();
      }
   }
   
   
/*
    * 重新接合一个 Hibernate Session 到当前线程.
    * @param session The Hibernate Session to be reconnected.
    */
   public static void reconnect(Session session)
      
throws InfrastructureException {
         
try {
         session.reconnect();
         threadSession.set(session);
         }
catch (HibernateException ex) {
         
throw new InfrastructureException(ex);
      }
   }
   
   
/*
    * 从当前线程分离并返回一个Hibernate Session.
    * Disconnect and return Session from current Thread.
    *
    * @return Session the disconnected Session
    */
   public static Session disconnectSession()
      
throws InfrastructureException {
      
      Session session = getSession();
         
try {
         threadSession.set(null);
         
if (session.isConnected() && session.isOpen())
         session.disconnect();
         }
catch (HibernateException ex) {
         
throw new InfrastructureException(ex);
      }
      
return session;
   }
   
   
/*
    * Register a Hibernate interceptor with the current thread.
    * 在当前线程中注册一个Hibernate拦截机
    *


    * Every Session opened is opened with this interceptor after
    * registration. Has no effect if the current Session of the
    * thread is already open, effective on next close()/getSession().
    */
      public static void registerInterceptor(Interceptor interceptor) {
      threadInterceptor.set(interceptor);
   }
   
      
private static Interceptor getInterceptor() {
      Interceptor interceptor =
      (Interceptor) threadInterceptor.get();
      
return interceptor;
   }
   
   
}


    * 如果当前线程中没有打开的session ,打开一个新的session放入当前的活动线程。
    * @return Session
    */
   public static Session getSession()
      
throws InfrastructureException {
      Session s = (Session) threadSession.get();
         
try {
            
if (s == null) {
            log.debug("Opening
new Session for this thread.");
               
if (getInterceptor() != null) {
               log.debug("Using interceptor: " + getInterceptor().getClass());
               s = getSessionFactory().openSession(getInterceptor());
               }
else {
               s = getSessionFactory().openSession();
            }
            threadSession.set(s);
         }
         }
catch (HibernateException ex) {
         
throw new InfrastructureException(ex);
      }
      
return s;
   }
   
   
/*
    * 关闭当前活动线程中的session.
    */
   public static void closeSession()
      
throws InfrastructureException {
         
try {
         Session s = (Session) threadSession.get();
         threadSession.set(null);
            
if (s != null && s.isOpen()) {
            log.debug("Closing Session of this thread.");
            s.close();
         }
         }
catch (HibernateException ex) {
         
throw new InfrastructureException(ex);
      }
   }
   
   
/*
    * 开始一个新的数据库事务.
    */
   public static void beginTransaction()
      
throws InfrastructureException {
      Transaction tx = (Transaction) threadTransaction.get();
         
try {
            
if (tx == null) {
            log.debug("Starting
new database transaction in this thread.");
            tx = getSession().beginTransaction();
            threadTransaction.set(tx);
         }
         }
catch (HibernateException ex) {
         
throw new InfrastructureException(ex);
      }
   }
   
   
/*
    * 提交未决的数据库事务
    */
   public static void commitTransaction()
      
throws InfrastructureException {
      Transaction tx = (Transaction) threadTransaction.get();
         
try {
         
if ( tx != null && !tx.wasCommitted()
            && !tx.wasRolledBack() ) {
            log.debug("Committing database transaction of this thread.");
            tx.commit();
         }
         threadTransaction.set(null);
         }
catch (HibernateException ex) {
         rollbackTransaction();
         
throw new InfrastructureException(ex);
      }
   }
   
   
/*
    * 对数据库事务做回滚操作
    */
   public static void rollbackTransaction()
      
throws InfrastructureException {
      Transaction tx = (Transaction) threadTransaction.get();
         
try {
         threadTransaction.set(null);
            
if ( tx != null && !tx.wasCommitted() && !tx.wasRolledBack() ) {
            log.debug("Tyring to rollback database transaction of this thread.");
            tx.rollback();
         }
         }
catch (HibernateException ex) {
         
throw new InfrastructureException(ex);
         } finally {
         closeSession();
      }
   }
   
   
/*
    * 重新接合一个 Hibernate Session 到当前线程.
    * @param session The Hibernate Session to be reconnected.
    */
   public static void reconnect(Session session)
      
throws InfrastructureException {
         
try {
         session.reconnect();
         threadSession.set(session);
         }
catch (HibernateException ex) {
         
throw new InfrastructureException(ex);
      }
   }
   
   
/*
    * 从当前线程分离并返回一个Hibernate Session.
    * Disconnect and return Session from current Thread.
    *
    * @return Session the disconnected Session
    */
   public static Session disconnectSession()
      
throws InfrastructureException {
      
      Session session = getSession();
         
try {
         threadSession.set(null);
         
if (session.isConnected() && session.isOpen())
         session.disconnect();
         }
catch (HibernateException ex) {
         
throw new InfrastructureException(ex);
      }
      
return session;
   }
   
   
/*
    * Register a Hibernate interceptor with the current thread.
    * 在当前线程中注册一个Hibernate拦截机
    *


    * Every Session opened is opened with this interceptor after
    * registration. Has no effect if the current Session of the
    * thread is already open, effective on next close()/getSession().
    */
      public static void registerInterceptor(Interceptor interceptor) {
      threadInterceptor.set(interceptor);
   }
   
      
private static Interceptor getInterceptor() {
      Interceptor interceptor =
      (Interceptor) threadInterceptor.get();
      
return interceptor;
   }
   
   
}


    * Every Session opened is opened with this interceptor after
    * registration. Has no effect if the current Session of the
    * thread is already open, effective on next close()/getSession().
    */
      public static void registerInterceptor(Interceptor interceptor) {
      threadInterceptor.set(interceptor);
   }
   
      
private static Interceptor getInterceptor() {
      Interceptor interceptor =
      (Interceptor) threadInterceptor.get();
      
return interceptor;
   }
   
   
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值