这几天在学习Spring4MVC集成Hibernate4,其中遇到了一个比较大的困惑,就是调用sessionFactory的getCurrentSession方法时,session不为空,但是sql语句就是不执行,在Hibernate文档中有这么一段话Remember that we switched the configuration option for this mechanism to "thread" in our
src/main/resources/hibernate.cfg.xml
? Due to that setting, the context of a current unit of work is bound to the current Java thread that executes the application.,自然似乎配置了<prop key="hibernate.current_session_context_class">thread</prop>这一项之后getCurrentSession就可以工作了。结果不然,配置了这段内容之后,调用Hibernate操作时候,则会提示xxxx
is not valid without active transaction,提示没有活动的事务。事实很显然了,SpringMVC不支持thread配置。自然,Spring中有默认的配置就是org.springframework.orm.hibernate4.SpringSessionContext,因此想起了Spring对Hibernate4取消了HibernateTemplate这个类,自然就不要说HibernateDaoSupport了,原因是Hibernate4在事务方面的支持已经很好了,所以,想起了Spring的annotation注解@Transactional(一般我们会把这个注解加到Service层),因此就考虑用这个处理,经检测,事实可行,即在SpringMVC中成功使用了getCurrentSession方法