Spring4+Hibernate4+测试驱动开发时发现的问题:No session (上)

在Service层上配置了切面加入了事务控制,但是在Dao层上没有配置事务。

用Spring-test编写了测试Dao的类,但是运行的时候报错:

org.hibernate.HibernateException: No Session found for current thread
 at org.springframework.orm.hibernate4.SpringSessionContext.currentSession(SpringSessionContext.java:106)
 at org.hibernate.internal.SessionFactoryImpl.getCurrentSession(SessionFactoryImpl.java:1012)

首先,不存在线程绑定的问题,我没有配置<prop key="hibernate.current_session_context_class">这个参数,注意是根本没加上这句话。

其次,也不存在Spring context之间的冲突问题。

最后发现问题出在SessionFactory.getCurrentSession必须放在事务中进行。在本文面对的问题上,因为是使用Spring test进行测试用例的编写,所以可以采用@Transactional标签对要测试的Dao进行事务管理。

这个事情挺神奇的,明天结合Spring和Hibernate的源码看看它们是怎么管理Session和事务的。

猜你喜欢

转载自whywjf.iteye.com/blog/2007540