KickJava   Java API By Example, From Geeks To Geeks.

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


1 /*
2  * Shark Hibernate Process Locking - Open Wide
3  */

4
5 package org.enhydra.shark.processlocking;
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    private static final ThreadLocal JavaDoc threadLocal = new ThreadLocal JavaDoc();
17
18    static {
19       try {
20          sessionFactory = new Configuration().configure(
21             "/hibernate.processlocking.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       Session session = (Session) threadLocal.get();
30       // Open a new Session, if this Thread has none yet
31
if (session == null) {
32          session = sessionFactory.openSession();
33          threadLocal.set(session);
34       }
35       if (!session.isConnected()){
36          session.reconnect();
37       }
38       return session;
39    }
40    public static void closeSession() throws HibernateException {
41       Session session = (Session) threadLocal.get();
42       threadLocal.set(null);
43       if (session != null)
44          session.close();
45    }
46 }
47
Popular Tags