01: package org.mdarad.framework.dao;
02:
03: import org.hibernate.HibernateException;
04: import org.hibernate.Session;
05: import org.hibernate.SessionFactory;
06: import org.hibernate.cfg.Configuration;
07:
08: public abstract class HibernateDAO implements DataAccessObject {
09: private static final SessionFactory sessionFactory;
10:
11: private static final ThreadLocal session = new ThreadLocal();
12:
13: static {
14: try {
15: // Create the SessionFactory
16: sessionFactory = new Configuration().configure()
17: .buildSessionFactory();
18: } catch (HibernateException ex) {
19: ex.printStackTrace(System.out);
20: throw new RuntimeException(
21: "Hibernate configuration problem : "
22: + ex.getMessage(), ex);
23: }
24: }
25:
26: public static Session currentSession() throws DAOException {
27: Session s = (Session) session.get();
28: try {
29: // Open a new Session, if this Thread has none yet
30: if (s == null) {
31: s = sessionFactory.openSession();
32: session.set(s);
33: }
34: } catch (HibernateException he) {
35: throw new DAOException(he);
36: }
37: return s;
38: }
39:
40: public static void closeSession() throws DAOException {
41: Session s = (Session) session.get();
42: session.set(null);
43: try {
44: if (s != null)
45: s.close();
46: } catch (HibernateException he) {
47: throw new DAOException(he);
48: }
49: }
50: }
|