KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > cash > util > HibernateUtil


1 package cash.util;
2
3
4
5 import net.sf.hibernate.HibernateException;
6
7 import net.sf.hibernate.SessionFactory;
8
9 import net.sf.hibernate.Session;
10
11 import net.sf.hibernate.cfg.Configuration;
12
13
14
15 import org.apache.log4j.Logger;
16
17
18
19 /**
20
21  * Helper Singleton class to manage Hibernate Sessions.
22
23  *
24
25  * @author Joel Hockey
26
27  * @version $Id: HibernateUtil.java,v 1.1 2005/03/21 04:16:09 plightbo Exp $
28
29  */

30
31 public class HibernateUtil {
32
33
34
35     /** ThreadLocal Session Map */
36
37     public static final ThreadLocal JavaDoc MAP = new ThreadLocal JavaDoc();
38
39
40
41     private static final Logger LOG = Logger.getLogger(HibernateUtil.class);
42
43
44
45     private static final SessionFactory SESSION_FACTORY;
46
47
48
49     /** Make default construct private */
50
51     private HibernateUtil() { }
52
53
54
55     /** Loads Hibernate config. */
56
57     static {
58
59         try {
60
61             LOG.debug("HibernateUtil.static - loading config");
62
63             SESSION_FACTORY = new Configuration().configure().buildSessionFactory();
64
65             LOG.debug("HibernateUtil.static - end");
66
67         } catch (HibernateException ex) {
68
69             throw new RuntimeException JavaDoc("Exception building SessionFactory: " + ex.getMessage(), ex);
70
71         }
72
73     }
74
75
76
77     /**
78
79      * Gets Hibernate Session for current thread. When finished, users
80
81      * must return session using {@link #closeSession() closeSession()} method.
82
83      * @return Hibernate Session for current thread.
84
85      * @throws HibernateException if there is an error opening a new session.
86
87      */

88
89     public static Session currentSession() throws HibernateException {
90
91         Session s = (Session)MAP.get();
92
93         // Open a new Session, if this Thread has none yet
94

95         if (s == null) {
96
97             s = SESSION_FACTORY.openSession();
98
99             MAP.set(s);
100
101         }
102
103         return s;
104
105     }
106
107
108
109     /**
110
111      * Closes the Hibernate Session. Users must call this method after calling
112
113      * {@link #currentSession() currentSession()}.
114
115      * @throws HibernateException if session has problem closing.
116
117      */

118
119     public static void closeSession() throws HibernateException {
120
121         Session s = (Session)MAP.get();
122
123         MAP.set(null);
124
125         if (s != null) {
126
127             s.close();
128
129         }
130
131     }
132
133 }
Popular Tags