KickJava   Java API By Example, From Geeks To Geeks.

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


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

4
5 package org.enhydra.shark.partmappersistence;
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.participantmapping.cfg.xml").buildSessionFactory();
22       } catch (HibernateException ex) {
23          ex.printStackTrace();
24          throw new RootError("Exception building SessionFactory: "
25                                 + ex.getMessage(), ex);
26       }
27    }
28
29    public static Session currentSession() throws HibernateException {
30
31       Session session = (Session) threadLocal.get();
32       // Open a new Session, if this Thread has none yet
33
if (session == null) {
34          session = sessionFactory.openSession();
35          threadLocal.set(session);
36       }
37       if (!session.isConnected()){
38          session.reconnect();
39       }
40       return session;
41    }
42
43    public static void closeSession() throws HibernateException {
44       Session session = (Session) threadLocal.get();
45       threadLocal.set(null);
46       if (session != null)
47          session.close();
48    }
49 }
50
Popular Tags