openSession和getCurrentSession都是SessionFactory工厂类的方法
Configuration cfg = new Configuration().configure();//加载Hibernate配置文件
SessionFactory sessionfactory=cfg.buildSessionFactory();//实例化SessionFactory
Session s1=sessionfactory.openSession();//打开session
Session s2=sessionfactory.getCurrentSession();//获得session
区别如下:
1.opensession()即打开一个新的session,每次使用都是打开一个新的session对象,使用完需要close关闭掉;
2.getCurrentSession()即获取当前上下文一个session对象。当第一次使用此方法时,会自动产生一个session对象,并且连续使用多次时,得到的session都是同一个对象;简而言之就是:如果有已经使用的,用旧的,如果没有,建新的。在实际开发中,往往使用getCurrentSession多,因为一般是处理同一个事务。
如何绑定本地的session?
现在的Hibernate框架中,使用session对象开启事务,所以需要来传递session对象,框架提供了ThreadLocal的方式
(1)需要在hibernate.cfg.xml的配置文件中提供配置
<property name="hibernate.current_session_context_class">thread</property>
(2) 重新编写HibernateUtil的工具类,使用SessionFactory的getCurrentSession()方法,获取当前的Session对象。并且该Session对象不用手动关闭,线程结束了,会自动关闭。
public static Session getCurrentSession(){
return factory.getCurrentSession();
}
注意:想使用getCurrentSession()方法,必须要先配置才能使用。