session和线程绑定
将session和线程绑定,一个Session对应一个线程
方法一:
修改工具类
public class HibernateUtils { private static SessionFactory factory; private static ThreadLocal<Session> threadLocal=new ThreadLocal<Session>(); static{ try { Configuration configuration=new Configuration(); configuration.configure("hibernate.cmd.xml"); factory = configuration.buildSessionFactory(); }catch (ExceptionInInitializerError e){ throw new ExceptionInInitializerError("初始化SessionFactory失败,请检查配置文件"); } } public static Session getSession(){ Session s=threadLocal.get(); if (s==null) { threadLocal.set(factory.openSession()); } s=threadLocal.get(); return s; } }public class HibernateUtils { private static SessionFactory factory; private static ThreadLocal<Session> threadLocal=new ThreadLocal<Session>(); static{ try { Configuration configuration=new Configuration(); configuration.configure("hibernate.cmd.xml"); factory = configuration.buildSessionFactory(); }catch (ExceptionInInitializerError e){ throw new ExceptionInInitializerError("初始化SessionFactory失败,请检查配置文件"); } } public static Session getSession(){ Session s=threadLocal.get(); if (s==null) { threadLocal.set(factory.openSession()); } s=threadLocal.get(); return s; } }
方法一:
修改配置文件,工具类添加新方法
<!--绑定线程和session,实现一个session只有一个线程。--> <property name="hibernate.current_session_context_class">thread</property>
/** *从线程上获取session * 配置了线程和session绑定,才能用 * @return */ public static Session getCurrnetSession(){ return factory.getCurrentSession(); }
/** 当Session和线程绑定后,hibernate,会在事务提交后自动关闭session **/