01: package org.apache.turbine.util.hibernate;
02:
03: /*
04: * Copyright 2001-2004 The Apache Software Foundation.
05: *
06: * Licensed under the Apache License, Version 2.0 (the "License")
07: * you may not use this file except in compliance with the License.
08: * You may obtain a copy of the License at
09: *
10: * http://www.apache.org/licenses/LICENSE-2.0
11: *
12: * Unless required by applicable law or agreed to in writing, software
13: * distributed under the License is distributed on an "AS IS" BASIS,
14: * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15: * See the License for the specific language governing permissions and
16: * limitations under the License.
17: */
18:
19: import net.sf.hibernate.HibernateException;
20: import net.sf.hibernate.JDBCException;
21: import net.sf.hibernate.Session;
22: import net.sf.hibernate.SessionFactory;
23:
24: import org.apache.commons.logging.Log;
25: import org.apache.commons.logging.LogFactory;
26:
27: /**
28: * This class is used to get Hibernate Sessions and may
29: * also contain methods (in the future) to get DBConnections
30: * or Transactions from JNDI.
31: *
32: * @version $Id: HibernateUtils.java 221820 2004-02-27 05:12:43Z seade $
33: */
34: public class HibernateUtils {
35: //~ Static fields/initializers =============================================
36: public final static String SESSION_FACTORY = "hibernate/sessionFactory";
37: public static final ThreadLocal session = new ThreadLocal();
38: private static SessionFactory sf = null;
39: private static HibernateUtils me;
40: private static Log log = LogFactory.getLog(HibernateUtils.class);
41:
42: static {
43: try {
44: me = new HibernateUtils();
45: } catch (Exception e) {
46: log.fatal("Error occurred initializing HibernateUtils");
47: e.printStackTrace();
48: }
49: }
50:
51: //~ Constructors ===========================================================
52:
53: private HibernateUtils() throws HibernateException, JDBCException {
54: }
55:
56: //~ Methods ================================================================
57:
58: public static Session currentSession() throws PersistenceException {
59: Session s = (Session) session.get();
60:
61: if (s == null) {
62: s = PersistenceManager.openSession();
63: if (log.isDebugEnabled()) {
64: log.debug("Opened hibernate session.");
65: }
66:
67: session.set(s);
68: }
69:
70: return s;
71: }
72:
73: public static void closeSession() throws HibernateException,
74: JDBCException {
75: Session s = (Session) session.get();
76: session.set(null);
77:
78: if (s != null) {
79: if (s.isOpen()) {
80: s.flush();
81: s.close();
82:
83: if (log.isDebugEnabled()) {
84: log.debug("Closed hibernate session.");
85: }
86: }
87: } else {
88: log
89: .warn("Hibernate session was inadvertently already closed.");
90:
91: }
92: }
93: }
|