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 session = new ThreadLocal (); 12 13 static { 14 try { 15 sessionFactory = new Configuration().configure().buildSessionFactory(); 17 } catch (HibernateException ex) { 18 ex.printStackTrace(System.out); 19 throw new RuntimeException ("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 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 |