KickJava   Java API By Example, From Geeks To Geeks.

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


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

4
5 package org.enhydra.shark.transaction;
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 /**
14  * Class used to ensure that only one Session Factory is being instanciated
15  * @author Vladislav Pernin
16  */

17 public class ThreadLocalSession {
18
19    private static final SessionFactory sessionFactory;
20    public static final ThreadLocal JavaDoc threadLocal = new ThreadLocal JavaDoc();
21
22    static {
23       try {
24          sessionFactory = new Configuration().configure(
25             "/hibernate.instance.cfg.xml").buildSessionFactory();
26       } catch (HibernateException ex) {
27          throw new RootError("Exception building SessionFactory: "
28                                 + ex.getMessage(), ex);
29       }
30    }
31
32    public static Session currentSession() throws HibernateException {
33       Session session = (Session) threadLocal.get();
34       // Open a new Session, if this Thread has none yet
35
if (session == null) {
36          session = sessionFactory.openSession();
37          threadLocal.set(session);
38       }
39       if (!session.isConnected()){
40          session.reconnect();
41       }
42       return session;
43
44    }
45
46    public static void closeSession() throws HibernateException {
47       Session session = (Session) threadLocal.get();
48       threadLocal.set(null);
49       if (session != null)
50          session.close();
51    }
52
53 }
54
Popular Tags