hibernate常用操作封装

hibernate常用操作封装
Java代码 复制代码
  1. package org.hibernate.auction.persistence;   
  2.   
  3. import net.sf.hibernate.*;   
  4. import net.sf.hibernate.cfg.Configuration;   
  5. import org.apache.commons.logging.*;   
  6. import org.hibernate.auction.exceptions.InfrastructureException;   
  7.   
  8. import javax.naming.*;   
  9.   
  10. /**  
  11.  * Basic Hibernate helper class, handles SessionFactory, Session and Transaction.  
  12.  * <p>  
  13.  * Uses a static initializer for the initial SessionFactory creation  
  14.  * and holds Session and Transactions in thread local variables. All  
  15.  * exceptions are wrapped in an unchecked InfrastructureException.  
  16.  *  
  17.  * @author christian@hibernate.org  
  18.  */  
  19. public class HibernateUtil {   
  20.   
  21.     private static Log log = LogFactory.getLog(HibernateUtil.class);   
  22.   
  23.     private static Configuration configuration;   
  24.     private static SessionFactory sessionFactory;   
  25.     private static final ThreadLocal threadSession = new ThreadLocal();   
  26.     private static final ThreadLocal threadTransaction = new ThreadLocal();   
  27.     private static final ThreadLocal threadInterceptor = new ThreadLocal();   
  28.   
  29.     // Create the initial SessionFactory from the default configuration files   
  30.     static {   
  31.         try {   
  32.             configuration = new Configuration();   
  33.             sessionFactory = configuration.configure().buildSessionFactory();   
  34.             // We could also let Hibernate bind it to JNDI:   
  35.             // configuration.configure().buildSessionFactory()   
  36.         } catch (Throwable ex) {   
  37.             // We have to catch Throwable, otherwise we will miss   
  38.             // NoClassDefFoundError and other subclasses of Error   
  39.             log.error("Building SessionFactory failed.", ex);   
  40.             throw new ExceptionInInitializerError(ex);   
  41.         }   
  42.     }   
  43.   
  44.     /**  
  45.      * Returns the SessionFactory used for this static class.  
  46.      *  
  47.      * @return SessionFactory  
  48.      */  
  49.     public static SessionFactory getSessionFactory() {   
  50.         /* Instead of a static variable, use JNDI:  
  51.         SessionFactory sessions = null;  
  52.         try {  
  53.             Context ctx = new InitialContext();  
  54.             String jndiName = "java:hibernate/HibernateFactory";  
  55.             sessions = (SessionFactory)ctx.lookup(jndiName);  
  56.         } catch (NamingException ex) {  
  57.             throw new InfrastructureException(ex);  
  58.         }  
  59.         return sessions;  
  60.         */  
  61.         return sessionFactory;   
  62.     }   
  63.   
  64.     /**  
  65.      * Returns the original Hibernate configuration.  
  66.      *  
  67.      * @return Configuration  
  68.      */  
  69.     public static Configuration getConfiguration() {   
  70.         return configuration;   
  71.     }   
  72.   
  73.     /**  
  74.      * Rebuild the SessionFactory with the static Configuration.  
  75.      *  
  76.      */  
  77.      public static void rebuildSessionFactory()   
  78.         throws InfrastructureException {   
  79.         synchronized(sessionFactory) {   
  80.             try {   
  81.                 sessionFactory = getConfiguration().buildSessionFactory();   
  82.             } catch (Exception ex) {   
  83.                 throw new InfrastructureException(ex);   
  84.             }   
  85.         }   
  86.      }   
  87.   
  88.     /**  
  89.      * Rebuild the SessionFactory with the given Hibernate Configuration.  
  90.      *  
  91.      * @param cfg  
  92.      */  
  93.      public static void rebuildSessionFactory(Configuration cfg)   
  94.         throws InfrastructureException {   
  95.         synchronized(sessionFactory) {   
  96.             try {   
  97.                 sessionFactory = cfg.buildSessionFactory();   
  98.                 configuration = cfg;   
  99.             } catch (Exception ex) {   
  100.                 throw new InfrastructureException(ex);   
  101.             }   
  102.         }   
  103.      }   
  104.   
  105.     /**  
  106.      * Retrieves the current Session local to the thread.  
  107.      * <p/>  
  108.      * If no Session is open, opens a new Session for the running thread.  
  109.      *  
  110.      * @return Session  
  111.      */  
  112.     public static Session getSession()   
  113.         throws InfrastructureException {   
  114.         Session s = (Session) threadSession.get();   
  115.         try {   
  116.             if (s == null) {   
  117.                 log.debug("Opening new Session for this thread.");   
  118.                 if (getInterceptor() != null) {   
  119.                     log.debug("Using interceptor: " + getInterceptor().getClass());   
  120.                     s = getSessionFactory().openSession(getInterceptor());   
  121.                 } else {   
  122.                     s = getSessionFactory().openSession();   
  123.                 }   
  124.                 threadSession.set(s);   
  125.             }   
  126.         } catch (HibernateException ex) {   
  127.             throw new InfrastructureException(ex);   
  128.         }   
  129.         return s;   
  130.     }   
  131.   
  132.     /**  
  133.      * Closes the Session local to the thread.  
  134.      */  
  135.     public static void closeSession()   
  136.         throws InfrastructureException {   
  137.         try {   
  138.             Session s = (Session) threadSession.get();   
  139.             threadSession.set(null);   
  140.             if (s != null && s.isOpen()) {   
  141.                 log.debug("Closing Session of this thread.");   
  142.                 s.close();   
  143.             }   
  144.         } catch (HibernateException ex) {   
  145.             throw new InfrastructureException(ex);   
  146.         }   
  147.     }   
  148.   
  149.     /**  
  150.      * Start a new database transaction.  
  151.      */  
  152.     public static void beginTransaction()   
  153.         throws InfrastructureException {   
  154.         Transaction tx = (Transaction) threadTransaction.get();   
  155.         try {   
  156.             if (tx == null) {   
  157.                 log.debug("Starting new database transaction in this thread.");   
  158.                 tx = getSession().beginTransaction();   
  159.                 threadTransaction.set(tx);   
  160.             }   
  161.         } catch (HibernateException ex) {   
  162.             throw new InfrastructureException(ex);   
  163.         }   
  164.     }   
  165.   
  166.     /**  
  167.      * Commit the database transaction.  
  168.      */  
  169.     public static void commitTransaction()   
  170.         throws InfrastructureException {   
  171.         Transaction tx = (Transaction) threadTransaction.get();   
  172.         try {   
  173.             if ( tx != null && !tx.wasCommitted()   
  174.                             && !tx.wasRolledBack() ) {   
  175.                 log.debug("Committing database transaction of this thread.");   
  176.                 tx.commit();   
  177.             }   
  178.             threadTransaction.set(null);   
  179.         } catch (HibernateException ex) {   
  180.             rollbackTransaction();   
  181.             throw new InfrastructureException(ex);   
  182.         }   
  183.     }   
  184.   
  185.     /**  
  186.      * Commit the database transaction.  
  187.      */  
  188.     public static void rollbackTransaction()   
  189.         throws InfrastructureException {   
  190.         Transaction tx = (Transaction) threadTransaction.get();   
  191.         try {   
  192.             threadTransaction.set(null);   
  193.             if ( tx != null && !tx.wasCommitted() && !tx.wasRolledBack() ) {   
  194.                 log.debug("Tyring to rollback database transaction of this thread.");   
  195.                 tx.rollback();   
  196.             }   
  197.         } catch (HibernateException ex) {   
  198.             throw new InfrastructureException(ex);   
  199.         } finally {   
  200.             closeSession();   
  201.         }   
  202.     }   
  203.   
  204.     /**  
  205.      * Reconnects a Hibernate Session to the current Thread.  
  206.      *  
  207.      * @param session The Hibernate Session to be reconnected.  
  208.      */  
  209.     public static void reconnect(Session session)   
  210.         throws InfrastructureException {   
  211.         try {   
  212.             session.reconnect();   
  213.             threadSession.set(session);   
  214.         } catch (HibernateException ex) {   
  215.             throw new InfrastructureException(ex);   
  216.         }   
  217.     }   
  218.   
  219.     /**  
  220.      * Disconnect and return Session from current Thread.  
  221.      *  
  222.      * @return Session the disconnected Session  
  223.      */  
  224.     public static Session disconnectSession()   
  225.         throws InfrastructureException {   
  226.   
  227.         Session session = getSession();   
  228.         try {   
  229.             threadSession.set(null);   
  230.             if (session.isConnected() && session.isOpen())   
  231.                 session.disconnect();   
  232.         } catch (HibernateException ex) {   
  233.             throw new InfrastructureException(ex);   
  234.         }   
  235.         return session;   
  236.     }   
  237.   
  238.     /**  
  239.      * Register a Hibernate interceptor with the current thread.  
  240.      * <p>  
  241.      * Every Session opened is opened with this interceptor after  
  242.      * registration. Has no effect if the current Session of the  
  243.      * thread is already open, effective on next close()/getSession().  
  244.      */  
  245.     public static void registerInterceptor(Interceptor interceptor) {   
  246.         threadInterceptor.set(interceptor);   
  247.     }   
  248.   
  249.     private static Interceptor getInterceptor() {   
  250.         Interceptor interceptor =   
  251.             (Interceptor) threadInterceptor.get();   
  252.         return interceptor;   
  253.     }   
  254.   
  255. }  
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值