KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > enhydra > shark > appmappersistence > ThreadLocalSession


1 /*
2  * Shark Hibernate ThreadLocalSession AppMapPersistence - Open Wide
3  */

4
5 package org.enhydra.shark.appmappersistence;
6
7 import net.sf.hibernate.HibernateException;
8 import net.sf.hibernate.Session;
9 import net.sf.hibernate.SessionFactory;
10 import net.sf.hibernate.cfg.Configuration;
11 import org.enhydra.shark.api.RootError;
12
13 public class ThreadLocalSession {
14
15    private static final SessionFactory sessionFactory;
16    public static final ThreadLocal JavaDoc threadLocal = new ThreadLocal JavaDoc();
17
18    static {
19       try {
20          sessionFactory = new Configuration().configure(
21             "/hibernate.applicationmapping.cfg.xml").buildSessionFactory();
22       } catch (HibernateException ex) {
23          throw new RootError("Exception building SessionFactory: "
24                                 + ex.getMessage(), ex);
25       }
26    }
27
28    public static Session currentSession() throws HibernateException {
29
30       Session session = (Session) threadLocal.get();
31       // Open a new Session, if this Thread has none yet
32
if (session == null) {
33          session = sessionFactory.openSession(new AppMappingsInterceptor());
34          threadLocal.set(session);
35       }
36       if (!session.isConnected()){
37          session.reconnect();
38       }
39       return session;
40    }
41
42    public static void closeSession() throws HibernateException {
43       Session session = (Session) threadLocal.get();
44       threadLocal.set(null);
45       if (session != null)
46          session.close();
47    }
48 }
49
Popular Tags