KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > mdarad > framework > dao > HibernateDAO


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