KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > de > nava > informa > utils > manager > hibernate > HibernateUtil


1 //
2
// Informa -- RSS Library for Java
3
// Copyright (c) 2002 by Niko Schmuck
4
//
5
// Niko Schmuck
6
// http://sourceforge.net/projects/informa
7
// mailto:niko_schmuck@users.sourceforge.net
8
//
9
// This library is free software.
10
//
11
// You may redistribute it and/or modify it under the terms of the GNU
12
// Lesser General Public License as published by the Free Software Foundation.
13
//
14
// Version 2.1 of the license should be included with this distribution in
15
// the file LICENSE. If the license is not included with this distribution,
16
// you may find a copy at the FSF web site at 'www.gnu.org' or 'www.fsf.org',
17
// or you may write to the Free Software Foundation, 675 Mass Ave, Cambridge,
18
// MA 02139 USA.
19
//
20
// This library is distributed in the hope that it will be useful,
21
// but WITHOUT ANY WARRANTY; without even the implied waranty of
22
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
23
// Lesser General Public License for more details.
24
//
25
// $Id: HibernateUtil.java,v 1.1 2004/09/02 09:13:08 spyromus Exp $
26
//
27

28 package de.nava.informa.utils.manager.hibernate;
29
30 import de.nava.informa.impl.hibernate.SessionHandler;
31 import de.nava.informa.utils.manager.PersistenceManagerException;
32 import net.sf.hibernate.HibernateException;
33 import net.sf.hibernate.LockMode;
34 import net.sf.hibernate.Session;
35
36 import java.util.logging.Level JavaDoc;
37 import java.util.logging.Logger JavaDoc;
38
39 /**
40  * Hibernate session utility. Using it to get sessions you will ensure
41  * that only session is created only once per thread.
42  *
43  * @author Aleksey Gureev (spyromus@noizeramp.com)
44  */

45 final class HibernateUtil {
46
47   private static final Logger JavaDoc LOG = Logger.getLogger(HibernateUtil.class.getName());
48
49   private static SessionHandler sessionHandler;
50   private static final ThreadLocal JavaDoc SESSION = new ThreadLocal JavaDoc();
51   private static boolean inited = false;
52
53   private static Object JavaDoc lock = new Object JavaDoc();
54   private static boolean sessionOpened = false;
55
56   /**
57    * Hidden constructor of utility class.
58    */

59   private HibernateUtil() {
60   }
61
62   /**
63    * Performs initialization.
64    *
65    * @throws HibernateException if problems with Hibernate occur.
66    */

67   private static void init()
68     throws HibernateException {
69
70     // Create the SessionFactory
71
sessionHandler = SessionHandler.getInstance(System.getProperties());
72     inited = true;
73   }
74
75   /**
76    * Opens new session or returns currently open session for this thread.
77    *
78    * @return session object.
79    *
80    * @throws HibernateException if something with session creation goes wrong.
81    */

82   public static synchronized Session openSession() throws HibernateException {
83     if (!inited) {
84       init();
85     }
86
87     synchronized (lock) {
88       if (sessionOpened) {
89         try {
90           lock.wait();
91         } catch (InterruptedException JavaDoc e) {
92           // Ok we can go.
93
}
94       }
95     }
96
97     Session s = (Session) SESSION.get();
98
99     // Open a new Session, if this Thread has none yet
100
if (s == null) {
101       s = sessionHandler.getSession();
102       SESSION.set(s);
103     }
104
105     sessionOpened = true;
106
107     return s;
108   }
109
110   /**
111    * Closes previousely opened session.
112    */

113   public static void closeSession() {
114     Session s = (Session) SESSION.get();
115
116     SESSION.set(null);
117
118     if (s != null) {
119       try {
120         s.close();
121       } catch (HibernateException e) {
122         // We can do nothing here.
123
// The other session will be opened next time.
124
}
125     }
126
127     synchronized (lock) {
128       sessionOpened = false;
129       lock.notify();
130     }
131   }
132
133   /**
134    * Makes a try to lock object. This will save us great number of SQL statements
135    * in several cases. It's not a big problem if locking is not possible.
136    *
137    * @param o object to lock.
138    * @param s session to lock object in.
139    */

140   public static void lock(Object JavaDoc o, Session s) {
141     try {
142       s.lock(o, LockMode.NONE);
143     } catch (HibernateException e) {
144       // Well, it's possible that object is dirty.
145
}
146   }
147
148   /**
149    * Saves object into storage.
150    *
151    * @param object object to save.
152    *
153    * @throws PersistenceManagerException in case of any problems during saving.
154    */

155   public static void saveObject(final Object JavaDoc object)
156     throws PersistenceManagerException {
157
158     // Save object in new session
159
saveObject(object, null);
160   }
161
162   /**
163    * Saves object into storage.
164    *
165    * @param object object to save.
166    *
167    * @throws PersistenceManagerException in case of any problems during saving.
168    */

169   public static void saveObject(final Object JavaDoc object, Session session)
170     throws PersistenceManagerException {
171     boolean isForeignSession = session != null;
172
173     try {
174       // Open new session if we are not in the foreign one
175
if (!isForeignSession) {
176         session = openSession();
177       }
178
179       session.save(object);
180
181       // Flush only if it's our own session
182
if (!isForeignSession) {
183         session.flush();
184         session.connection().commit();
185       }
186     } catch (Exception JavaDoc e) {
187       // Rollback transaction if we are owners of session
188
if (!isForeignSession) {
189         try {
190           session.connection().rollback();
191         } catch (Exception JavaDoc e1) {
192           // Error is not recoverable.
193
}
194       }
195
196       LOG.log(Level.SEVERE, "Couldn't save object.", e);
197       throw new PersistenceManagerException("Couldn't save object.", e);
198     } finally {
199       // Close session if we had opened it
200
if (!isForeignSession) {
201         closeSession();
202       }
203     }
204   }
205
206   /**
207    * Updates object in storage.
208    *
209    * @param object object to update.
210    *
211    * @throws PersistenceManagerException in case of any problems during updating.
212    */

213   public static void updateObject(final Object JavaDoc object)
214     throws PersistenceManagerException {
215
216     updateObject(object, null);
217   }
218
219   /**
220    * Updates object in storage.
221    *
222    * @param object object to update.
223    * @param session session to use. If NULL then new session is opened.
224    *
225    * @throws PersistenceManagerException in case of any problems during updating.
226    */

227   public static void updateObject(final Object JavaDoc object, Session session)
228     throws PersistenceManagerException {
229
230     boolean isForeignSession = session != null;
231
232     try {
233       // Open new session if we are not in the foreign one
234
if (!isForeignSession) {
235         session = openSession();
236       }
237
238       session.update(object);
239
240       // Flush only if it's our own session
241
if (!isForeignSession) {
242         session.flush();
243         session.connection().commit();
244       }
245     } catch (Exception JavaDoc e) {
246       // Rollback transaction if we are owners of session
247
if (!isForeignSession) {
248         try {
249           session.connection().rollback();
250         } catch (Exception JavaDoc e1) {
251           // Error is not recoverable.
252
}
253       }
254
255       LOG.log(Level.SEVERE, "Couldn't update object.", e);
256       throw new PersistenceManagerException("Couldn't update object.", e);
257     } finally {
258       // Close session if we had opened it
259
if (!isForeignSession) {
260         closeSession();
261       }
262     }
263   }
264
265   /**
266    * Deletes object from database using existing session.
267    *
268    * @param object object to delete.
269    * @param session session to use. If NULL then new session is opened.
270    *
271    * @throws PersistenceManagerException in case of any problems during deletion.
272    */

273   public static void deleteObject(final Object JavaDoc object, Session session)
274     throws PersistenceManagerException {
275
276     boolean isForeignSession = session != null;
277
278     try {
279       // Open new session if we are not in the foreign one
280
if (!isForeignSession) {
281         session = openSession();
282       }
283
284       session.delete(object);
285
286       // Flush only if it's our own session
287
if (!isForeignSession) {
288         session.flush();
289         session.connection().commit();
290       }
291     } catch (Exception JavaDoc e) {
292       // Rollback transaction if we are owners of session
293
if (!isForeignSession) {
294         try {
295           session.connection().rollback();
296         } catch (Exception JavaDoc e1) {
297           // Error is not recoverable.
298
}
299       }
300       LOG.log(Level.SEVERE, "Couldn't delete object.", e);
301       throw new PersistenceManagerException("Couldn't delete object.", e);
302     } finally {
303       // Close session if we had opened it
304
if (!isForeignSession) {
305         closeSession();
306       }
307     }
308   }
309 }
310
Popular Tags