Advertisement
Guest User

hibernateutil

a guest
Apr 11th, 2012
150
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 7.58 KB | None | 0 0
  1. /*
  2.  * To change this template, choose Tools | Templates
  3.  * and open the template in the editor.
  4.  */
  5.  
  6. package vas.framework.hibernate;
  7.  
  8. /**
  9.  *
  10.  * @author Necati Demir
  11.  */
  12.  
  13.  
  14. import org.apache.commons.logging.*;
  15. import org.hibernate.HibernateException;
  16. import org.hibernate.Interceptor;
  17. import org.hibernate.Session;
  18. import org.hibernate.SessionFactory;
  19. import org.hibernate.Transaction;
  20. import org.hibernate.cfg.Configuration;
  21. //import vas.framework.exceptions.InfrastructureException;
  22.  
  23.  
  24. public class HibernateUtil {
  25.  
  26.     private static Log log = LogFactory.getLog(HibernateUtil.class);
  27.  
  28.     private static Configuration configuration;
  29.     private static SessionFactory sessionFactory;
  30.     private static final ThreadLocal threadSession = new ThreadLocal();
  31.     private static final ThreadLocal threadTransaction = new ThreadLocal();
  32.     private static final ThreadLocal threadInterceptor = new ThreadLocal();
  33.  
  34.     // Create the initial SessionFactory from the default configuration files
  35.     static {
  36.         try {
  37.             configuration = new Configuration().configure("/hermes/db/config/tcksmssender.cfg.xml");
  38.                         sessionFactory = configuration.buildSessionFactory();
  39.  
  40.             //sessionFactory = configuration.configure("/hermes/db/config/tcksmssender.cfg.xml").buildSessionFactory();
  41.             // We could also let Hibernate bind it to JNDI:
  42.             // configuration.configure().buildSessionFactory()
  43.         } catch (Exception ex) {
  44.             // We have to catch Throwable, otherwise we will miss
  45.             // NoClassDefFoundError and other subclasses of Error
  46.             //log.error("Building SessionFactory failed.", ex);
  47.             //throw new ExceptionInInitializerError(ex);
  48.                         ex.printStackTrace();
  49.         }
  50.     }
  51.  
  52.     /**
  53.      * Returns the SessionFactory used for this static class.
  54.      *
  55.      * @return SessionFactory
  56.      */
  57.     public static SessionFactory getSessionFactory() {
  58.         /* Instead of a static variable, use JNDI:
  59.         SessionFactory sessions = null;
  60.         try {
  61.             Context ctx = new InitialContext();
  62.             String jndiName = "java:hibernate/HibernateFactory";
  63.             sessions = (SessionFactory)ctx.lookup(jndiName);
  64.         } catch (NamingException ex) {
  65.             throw new InfrastructureException(ex);
  66.         }
  67.         return sessions;
  68.         */
  69.         return sessionFactory;
  70.     }
  71.  
  72.     /**
  73.      * Returns the original Hibernate configuration.
  74.      *
  75.      * @return Configuration
  76.      */
  77.     public static Configuration getConfiguration() {
  78.         return configuration;
  79.     }
  80.  
  81.     /**
  82.      * Rebuild the SessionFactory with the static Configuration.
  83.      *
  84.      */
  85.      public static void rebuildSessionFactory()
  86.         /*throws InfrastructureException*/ {
  87.         synchronized(sessionFactory) {
  88.             try {
  89.                 sessionFactory = getConfiguration().buildSessionFactory();
  90.             } catch (Exception ex) {
  91.                             ex.printStackTrace();
  92. //              throw new InfrastructureException(ex);
  93.             }
  94.         }
  95.      }
  96.  
  97.     /**
  98.      * Rebuild the SessionFactory with the given Hibernate Configuration.
  99.      *
  100.      * @param cfg
  101.      */
  102.      public static void rebuildSessionFactory(Configuration cfg)
  103.         /*throws InfrastructureException*/ {
  104.         synchronized(sessionFactory) {
  105.             try {
  106.                 sessionFactory = cfg.buildSessionFactory();
  107.                 configuration = cfg;
  108.             } catch (Exception ex) {
  109.                             ex.printStackTrace();
  110. //              throw new InfrastructureException(ex);
  111.             }
  112.         }
  113.      }
  114.  
  115.     /**
  116.      * Retrieves the current Session local to the thread.
  117.      * <p/>
  118.      * If no Session is open, opens a new Session for the running thread.
  119.      *
  120.      * @return Session
  121.      */
  122.     public static Session getSession()
  123.         /*throws InfrastructureException*/ {
  124.         Session s = (Session) threadSession.get();
  125.         try {
  126.             if (s == null) {
  127.                                 System.out.println("Opening new Session for this thread.");
  128.                 if (getInterceptor() != null) {
  129.                     log.debug("Using interceptor: " + getInterceptor().getClass());
  130.                     s = getSessionFactory().openSession(getInterceptor());
  131.                 } else {
  132.                     s = getSessionFactory().openSession();
  133.                 }
  134.                 threadSession.set(s);
  135.             }
  136.         } catch (HibernateException ex) {
  137.                     ex.printStackTrace();
  138. //          throw new InfrastructureException(ex);
  139.         }
  140.         return s;
  141.     }
  142.  
  143.     /**
  144.      * Closes the Session local to the thread.
  145.      */
  146.     public static void closeSession()
  147.         /*throws InfrastructureException*/ {
  148.         try {
  149.             Session s = (Session) threadSession.get();
  150.             threadSession.set(null);
  151.             if (s != null && s.isOpen()) {
  152.                 log.debug("Closing Session of this thread.");
  153.                 s.close();
  154.             }
  155.         } catch (HibernateException ex) {
  156.                     ex.printStackTrace();
  157. //          throw new InfrastructureException(ex);
  158.         }
  159.     }
  160.  
  161.     /**
  162.      * Start a new database transaction.
  163.      */
  164.     public static void beginTransaction()
  165.         /*throws InfrastructureException*/ {
  166.         Transaction tx = (Transaction) threadTransaction.get();
  167.         try {
  168.             if (tx == null) {
  169.                 log.debug("Starting new database transaction in this thread.");
  170.                 tx = getSession().beginTransaction();
  171.                 threadTransaction.set(tx);
  172.             }
  173.         } catch (HibernateException ex) {
  174.                     ex.printStackTrace();
  175. //          throw new InfrastructureException(ex);
  176.         }
  177.     }
  178.  
  179.     /**
  180.      * Commit the database transaction.
  181.      */
  182.     public static void commitTransaction()
  183.         /*throws InfrastructureException*/ {
  184.         Transaction tx = (Transaction) threadTransaction.get();
  185.         try {
  186.             if ( tx != null && !tx.wasCommitted()
  187.                             && !tx.wasRolledBack() ) {
  188.                 log.debug("Committing database transaction of this thread.");
  189.                 tx.commit();
  190.             }
  191.             threadTransaction.set(null);
  192.         } catch (HibernateException ex) {
  193.             rollbackTransaction();
  194.                         ex.printStackTrace();
  195. //          throw new InfrastructureException(ex);
  196.         }
  197.     }
  198.  
  199.     /**
  200.      * Rollback the database transaction.
  201.      */
  202.     public static void rollbackTransaction()
  203.         /*throws InfrastructureException*/ {
  204.         Transaction tx = (Transaction) threadTransaction.get();
  205.         try {
  206.             threadTransaction.set(null);
  207.             if ( tx != null && !tx.wasCommitted() && !tx.wasRolledBack() ) {
  208.                 log.debug("Tyring to rollback database transaction of this thread.");
  209.                 tx.rollback();
  210.             }
  211.         } catch (HibernateException ex) {
  212.                     ex.printStackTrace();
  213. //          throw new InfrastructureException(ex);
  214.         } finally {
  215.             closeSession();
  216.         }
  217.     }
  218.  
  219.     /**
  220.      * Reconnects a Hibernate Session to the current Thread.
  221.      *
  222.      * @param session The Hibernate Session to be reconnected.
  223.      */
  224.     public static void reconnect(Session session)
  225.         /*throws InfrastructureException*/ {
  226.         try {
  227.             session.reconnect();
  228.             threadSession.set(session);
  229.         } catch (HibernateException ex) {
  230.                     ex.printStackTrace();
  231. //          throw new InfrastructureException(ex);
  232.         }
  233.     }
  234.  
  235.     /**
  236.      * Disconnect and return Session from current Thread.
  237.      *
  238.      * @return Session the disconnected Session
  239.      */
  240.     public static Session disconnectSession()
  241.         /*throws InfrastructureException*/ {
  242.  
  243.         Session session = getSession();
  244.         try {
  245.             threadSession.set(null);
  246.             if (session.isConnected() && session.isOpen())
  247.                 session.disconnect();
  248.         } catch (HibernateException ex) {
  249.                     ex.printStackTrace();
  250. //          throw new InfrastructureException(ex);
  251.         }
  252.         return session;
  253.     }
  254.  
  255.     /**
  256.      * Register a Hibernate interceptor with the current thread.
  257.      * <p>
  258.      * Every Session opened is opened with this interceptor after
  259.      * registration. Has no effect if the current Session of the
  260.      * thread is already open, effective on next close()/getSession().
  261.      */
  262.     public static void registerInterceptor(Interceptor interceptor) {
  263.         threadInterceptor.set(interceptor);
  264.     }
  265.  
  266.     private static Interceptor getInterceptor() {
  267.         Interceptor interceptor =
  268.             (Interceptor) threadInterceptor.get();
  269.         return interceptor;
  270.     }
  271.  
  272. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement