比较openSession()和getCurrentSession()方法通过SessionFactory获取session

  1. openSession()获取的是一个新的session
  2. 如果要使用getCurrentSession,需要在hibernate.cfg.xml文件中配置
<property name="curent_session_content_class">thread</property>

getCurrentSession获取和当前线程绑定的session,换言之,在同一个线程中,我们获取的session是同一个session,这样有利于事务控制
3. 通过getCurrentSession()获取的session在事物提交后会自动关闭,通过openSession()获取的session则需手动关闭
4. 如果通过getCurrentSession()获取的session进行查询时需要提交事务,openSession()可以不用提交事务

你可能感兴趣的:(session)