openSession 和getCurrentSession的区别

目前获取Session的时候存在两种方式,openSession和getCurrentSession,如下:

	<span style="white-space:pre">	</span>Configuration config = new Configuration();
		SessionFactory sessionFactory = config.buildSessionFactory();
		//方式一
		Session session1 = sessionFactory.openSession();
		//方式二
		Session session2 = sessionFactory.getCurrentSession();
两种方法的区别如下:

(1)openSession每次打开都是新的Session,所以多次获取的Session实例是不同的,并且需要人为的调用close方法进行Session关闭。

(2)getCurrentSession是从当前上下文中获取Session并且会绑定到当前线程,第一次调用时会创建一个Session实例,如果该Session未关闭,后续多次获取的是同一个Session实例;事务提交或者回滚时会自动关闭Sesison,无需人工关闭。

使用getCurrentSession时,需要在配置文件中添加如下:

(1)如果使用的是本地事务(JDBC事务)

<property name="current_session_context_class">thread</property>
(2)如果使用的是全局事务(JTA事务)

<property name="current_session_context_class">jta</property>



你可能感兴趣的:(Hibernate,sessionFactory,openSession)