KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > hibernate > ce > auction > persistence > HibernateUtil


1 package org.hibernate.ce.auction.persistence;
2
3 import org.hibernate.*;
4 import org.hibernate.cfg.*;
5 import org.apache.commons.logging.*;
6 import org.hibernate.ce.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 JavaDoc threadSession = new ThreadLocal JavaDoc();
26     private static final ThreadLocal JavaDoc threadTransaction = new ThreadLocal JavaDoc();
27     private static final ThreadLocal JavaDoc threadInterceptor = new ThreadLocal JavaDoc();
28
29     // Create the initial SessionFactory from the default configuration files
30
static {
31         try {
32             configuration = new AnnotationConfiguration();
33 // configuration = new Configuration();
34
sessionFactory = configuration.configure().buildSessionFactory();
35             // We could also let Hibernate bind it to JNDI:
36
// configuration.configure().buildSessionFactory()
37
} catch (Throwable JavaDoc ex) {
38             // We have to catch Throwable, otherwise we will miss
39
// NoClassDefFoundError and other subclasses of Error
40
log.error("Building SessionFactory failed.", ex);
41             throw new ExceptionInInitializerError JavaDoc(ex);
42         }
43     }
44
45     /**
46      * Returns the SessionFactory used for this static class.
47      *
48      * @return SessionFactory
49      */

50     public static SessionFactory getSessionFactory() {
51         /* Instead of a static variable, use JNDI:
52         SessionFactory sessions = null;
53         try {
54             Context ctx = new InitialContext();
55             String jndiName = "java:hibernate/HibernateFactory";
56             sessions = (SessionFactory)ctx.lookup(jndiName);
57         } catch (NamingException ex) {
58             throw new InfrastructureException(ex);
59         }
60         return sessions;
61         */

62         return sessionFactory;
63     }
64
65     /**
66      * Returns the original Hibernate configuration.
67      *
68      * @return Configuration
69      */

70     public static Configuration getConfiguration() {
71         return configuration;
72     }
73
74     /**
75      * Rebuild the SessionFactory with the static Configuration.
76      *
77      */

78      public static void rebuildSessionFactory()
79         throws InfrastructureException {
80         synchronized(sessionFactory) {
81             try {
82                 sessionFactory = getConfiguration().buildSessionFactory();
83             } catch (Exception JavaDoc ex) {
84                 throw new InfrastructureException(ex);
85             }
86         }
87      }
88
89     /**
90      * Rebuild the SessionFactory with the given Hibernate Configuration.
91      *
92      * @param cfg
93      */

94      public static void rebuildSessionFactory(Configuration cfg)
95         throws InfrastructureException {
96         synchronized(sessionFactory) {
97             try {
98                 sessionFactory = cfg.buildSessionFactory();
99                 configuration = cfg;
100             } catch (Exception JavaDoc ex) {
101                 throw new InfrastructureException(ex);
102             }
103         }
104      }
105
106     /**
107      * Retrieves the current Session local to the thread.
108      * <p/>
109      * If no Session is open, opens a new Session for the running thread.
110      *
111      * @return Session
112      */

113     public static Session getSession()
114         throws InfrastructureException {
115         Session s = (Session) threadSession.get();
116         try {
117             if (s == null) {
118                 log.debug("Opening new Session for this thread.");
119                 if (getInterceptor() != null) {
120                     log.debug("Using interceptor: " + getInterceptor().getClass());
121                     s = getSessionFactory().openSession(getInterceptor());
122                 } else {
123                     s = getSessionFactory().openSession();
124                 }
125                 threadSession.set(s);
126             }
127         } catch (HibernateException ex) {
128             throw new InfrastructureException(ex);
129         }
130         return s;
131     }
132
133     /**
134      * Closes the Session local to the thread.
135      */

136     public static void closeSession()
137         throws InfrastructureException {
138         try {
139             Session s = (Session) threadSession.get();
140             threadSession.set(null);
141             if (s != null && s.isOpen()) {
142                 log.debug("Closing Session of this thread.");
143                 s.close();
144             }
145         } catch (HibernateException ex) {
146             throw new InfrastructureException(ex);
147         }
148     }
149
150     /**
151      * Start a new database transaction.
152      */

153     public static void beginTransaction()
154         throws InfrastructureException {
155         Transaction tx = (Transaction) threadTransaction.get();
156         try {
157             if (tx == null) {
158                 log.debug("Starting new database transaction in this thread.");
159                 tx = getSession().beginTransaction();
160                 threadTransaction.set(tx);
161             }
162         } catch (HibernateException ex) {
163             throw new InfrastructureException(ex);
164         }
165     }
166
167     /**
168      * Commit the database transaction.
169      */

170     public static void commitTransaction()
171         throws InfrastructureException {
172         Transaction tx = (Transaction) threadTransaction.get();
173         try {
174             if ( tx != null && !tx.wasCommitted()
175                             && !tx.wasRolledBack() ) {
176                 log.debug("Committing database transaction of this thread.");
177                 tx.commit();
178             }
179             threadTransaction.set(null);
180         } catch (HibernateException ex) {
181             rollbackTransaction();
182             throw new InfrastructureException(ex);
183         }
184     }
185
186     /**
187      * Rollback the database transaction.
188      */

189     public static void rollbackTransaction()
190         throws InfrastructureException {
191         Transaction tx = (Transaction) threadTransaction.get();
192         try {
193             threadTransaction.set(null);
194             if ( tx != null && !tx.wasCommitted() && !tx.wasRolledBack() ) {
195                 log.debug("Tyring to rollback database transaction of this thread.");
196                 tx.rollback();
197             }
198         } catch (HibernateException ex) {
199             throw new InfrastructureException(ex);
200         } finally {
201             closeSession();
202         }
203     }
204
205     /**
206      * Reconnects a Hibernate Session to the current Thread.
207      *
208      * @param session The Hibernate Session to be reconnected.
209      */

210     public static void reconnect(Session session)
211         throws InfrastructureException {
212         try {
213             session.reconnect();
214             threadSession.set(session);
215         } catch (HibernateException ex) {
216             throw new InfrastructureException(ex);
217         }
218     }
219
220     /**
221      * Disconnect and return Session from current Thread.
222      *
223      * @return Session the disconnected Session
224      */

225     public static Session disconnectSession()
226         throws InfrastructureException {
227
228         Session session = getSession();
229         try {
230             threadSession.set(null);
231             if (session.isConnected() && session.isOpen())
232                 session.disconnect();
233         } catch (HibernateException ex) {
234             throw new InfrastructureException(ex);
235         }
236         return session;
237     }
238
239     /**
240      * Register a Hibernate interceptor with the current thread.
241      * <p>
242      * Every Session opened is opened with this interceptor after
243      * registration. Has no effect if the current Session of the
244      * thread is already open, effective on next close()/getSession().
245      */

246     public static void registerInterceptor(Interceptor interceptor) {
247         threadInterceptor.set(interceptor);
248     }
249
250     private static Interceptor getInterceptor() {
251         Interceptor interceptor =
252             (Interceptor) threadInterceptor.get();
253         return interceptor;
254     }
255
256 }
257
258
Popular Tags