- import org.hibernate.Session;
- import org.hibernate.SessionFactory;
- import org.hibernate.cfg.Configuration;
- public class HibernateSessionUtil {
-
- //private static Map<Thread, Session> sessionMap = new HashMap<Thread, Session>();
- private static ThreadLocal<Session> threadLocal = new ThreadLocal<Session>();
-
- private static SessionFactory sf;
-
- static {
- sf = new Configuration().configure().buildSessionFactory();
- }
-
- /**
- * 打开一个新的session,并自动与当前线程关联
- * @return
- */
- public static Session openSession() {
- Session session = sf.openSession();
- //sessionMap.put(Thread.currentThread(), session);
- threadLocal.set(session);
- return session;
- }
- /**
- * 获得当前线程关联的session,如果为空返回null
- * @return
- */
- public static Session getCurrentSession() {
- Session session = threadLocal.get();
- return session;
- }
- /**
- * 关闭当前线程关联的session,并自动移除先关联的session
- */
- public static void closeAndRomoveSession() {
- Session session = threadLocal.get();
- if(session != null) {
- threadLocal.remove();
- session.close();
- }
-
- }
-
-
- }
复制代码 注:这个是我以前用到的,不知何楼主的效果相同,需要结合hibernate配置和spring的内容,
主要是很长时间没有接触了,希望上面代码能给楼主以帮助。
|