1.Session類似于JDBC的連接Connection
2.Session對象是單線程對象,只能自己使用不能共用,將Session與本地線程綁定,保證Session對象絕對是一個單線程對象
3.Hibernate幫助我們實現(xiàn)了Session與本地綁定(底層是ThreadLocal)
4.獲取與本地線程綁定的Session
(1)在Hibernate核心配置文件中配置(hibernate.cfg.xml)
<property name="hibernate.current_session_context_class">thread</property>
(2)調(diào)用SessionFactory
在HibernateUtils.java中提供返回與本地線程綁定的session的方法
public static Session getCurrentSession(){
return sessionFactory.getCurrentSession();
}
//注意:獲取與本地綁定的session時,關(guān)閉session報錯,所以不需要手動關(guān)閉session.