1, 配置hibernate.cfg.xml
在hibernate.cfg.xml中增加一个语句
<!-- 把session和线程绑定,从而实现一个线程只有一个session -->
<property name="hibernate.current_session_context_class">thread</property>
2, 在工具类中增加一个getCurrentSession()方法
public class HibernateUtil {
private static SessionFactory factory;
//SessionFactory对象只有一个
static{
try {
Configuration cfg = new Configuration();
cfg.configure();
factory = cfg.buildSessionFactory();
} catch (ExceptionInInitializerError e) {
throw new ExceptionInInitializerError("初始化SessionFactory失败!");
}
}
/*
* 获取一个新的session对象
* 只要使用了openSession方法,每次都会得到一个新的session
*/
public static Session openSession(){
return factory.openSession();
}
/*
* 从当前线程上获取Session对象
*/
public static Session getCurrentSession(){
return factory.getCurrentSession();//只有配置了把session和线程绑定之后,才能使用该方法,否则返回null
}
}
3 , 验证session是否和线程绑定
public void test01(){
Session s1 = HibernateUtil.getCurrentSession();
Session s2 = HibernateUtil.getCurrentSession();
System.out.println(s1==s2);
//返回结果为true
}