我遇到了 Spring3 和 Hibernate4 的问题。我想使用@Transactional 来管理休眠事务。我的 JUnit 测试适用于 HSQDB。但是当部署在Tomcat上时,会发生异常。
我尝试了许多配置,其中一个适用于单元测试的配置包括删除会话工厂配置中的 hibernate.current_session_context_class 属性。然后在服务器模式下,出现以下异常:
org.hibernate.HibernateException: No Session found for current thread
at org.springframework.orm.hibernate4.SpringSessionContext.currentSession(SpringSessionContext.java:97)
at org.hibernate.internal.SessionFactoryImpl.getCurrentSession(SessionFactoryImpl.java:990)
at myproject.dao.impl.UserDaoImpl.create(UserDaoImpl.java:37)
当我将 hibernate.current_session_context_class 配置为值“线程”时,异常是:
org.hibernate.HibernateException: save is not valid without active transaction
at org.hibernate.context.internal.ThreadLocalSessionContext$TransactionProtectionWrapper.invoke(ThreadLocalSessionContext.java:348)
at com.sun.proxy.$Proxy25.save(Unknown Source)
at myproject.dao.impl.UserDaoImpl.create(UserDaoImpl.java:39)
这是我的配置:
<beans>
<context:annotation-config />
<tx:annotation-driven transaction-manager="transactionManager"/>
<jee:jndi-lookup id="dataSource" jndi-name="jdbc/MyDataSource"/>
<bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="packagesToScan">
<list>
<value>myproject.dao.entity</value>
</list>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.connection.pool_size">1</prop>
<prop key="hibernate.current_session_context_class">thread</prop>
<prop key="hibernate.hbm2ddl.auto">update</prop>
</props>
</property>
</bean>
<bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
</beans>