session
1、crud操作是由session完成的
2、与数据库的连接是由session打开的
3、对象的状态和一级缓存与session紧密相关
4、数据安全性的问题
打开session的方式
openSession
1、只要调用一次openSession方法都会打开一个新的连接
2、这种方式效率不是很高
3、利用这种方式很容器的就可以操作session的缓存
getCurrentSession
1、把session放入到threadlocal中,确保线程安全
2、在整个线程中可以共享session,并且该session只有一个
3、在threadlocal中存放Map
使用
hibernate.cfg.xml
<property name="current_session_context_class">thread</property>
public void TestCurrentSession()
{
//获取当前线程Session
Session session=sessionFactory.getCurrentSession();
//在CurrentSession中,就算是查询也要在失误范围内
Transaction transaction=session.beginTransaction();
Person person =(Person)session.get(Person.class,1L);
transaction.commit();
//在CurrentSession中 ,事务提交之后,session自动关闭
// session.close();
}
说明:
1、crud操作都必须在事务的条件下进行
2、当事务提交,session自动关闭