KickJava   Java API By Example, From Geeks To Geeks.

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


1 /*
2  * Shark Hibernate ThreadLocalSession ScriptPersistence - Copyright Open Wide
3  */

4
5 package org.enhydra.shark.scriptmappersistence;
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
17    public static final ThreadLocal JavaDoc threadLocal = new ThreadLocal JavaDoc();
18
19    static {
20       try {
21          sessionFactory = new Configuration().configure(
22             "/hibernate.script.cfg.xml").buildSessionFactory();
23       } catch (HibernateException ex) {
24          throw new RootError("Exception building SessionFactory: "
25                                 + ex.getMessage(), ex);
26       }
27    }
28
29    public static Session currentSession() throws HibernateException {
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();
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