我在一个事务里调用了两次getCurrentSession,就是this.getHibernateTemplate().getSessionFactory().getCurrentSession(),却打开了两个session,事务提交后只关闭了一个。如果我换成HibernateDaoSupport提供的方法操作却没有这个问题,只打开1个session提交后正常关闭。请问这是怎么回事?
我做了几个测试 如果使用this.getSession()则session正常关闭,调用多次也没问题。 如果使用this.getHibernateTemplate().getSessionFactory().getCurrentSession(),始终打开1个session并且不能关闭。 如果使用this.getHibernateTemplate().getSessionFactory().getSession(),调用几次打开几个session并且都不能关闭。 就是说,凡是通过this.getHibernateTemplate().getSessionFactory()获得的session都不在事务管理内。 我的spring的sessionFactory配置是这样的 <bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean"> <property name="configLocation" value="classpath:hibernate.cfg.xml"/> </bean> 因为如果使用this.getSession()正常,所以事务配置应该是没有问题的。 而且有一点,如果是通过this.getHibernateTemplate().getSessionFactory()获得的session必须要beginTransaction,而this.getSession()则不用。 我在dao里分别打印了两种途径获得的session的.getTransaction().isActive(), 很显然,getCurrentSession()的是false。