我正在尝试使用带有 Rest Template 的 Junit 来测试我的服务类。我的服务对数据库有多个调用,因此我将其标记为 @transaction 以使这些调用作为单个事务进行。但问题是如果其中任何一个调用失败或任何一个抛出异常,较早提交的调用应该回滚。但较早提交的事务不会回滚。
@Transactional
class A
{
@Autowired
B object
object.someMethod()//this method has logic to save the data
object.someOtherMethod()//this method will throws an Exception
}
@Transactional
class B
{
someOtherMethod()
{
//here it will throw an exception
}
}
这是我的部分 spring 配置文件
<tx:annotationdriven ref=transactionManager/>
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManagerFactoryBean"/>
</bean>
<bean id="entityManagerFactoryBean"
class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="dataSource" ref="dbDataSource" />
<property name="jpaVendorAdapter">
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter" />
</property>
<property name="jpaProperties">
<props>
<prop key="hibernate.hbm2ddl.auto">validate</prop>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQL5InnoDBDialect</prop>
<prop key="hibernate.connection.autocommit">false</prop>
</props>
</property>
</bean>
最佳答案
您是如何运行 JUnit 测试的?您是否像记录的那样使用 SpringJUnit4ClassRunner 运行它 here ? 如果不这样做,您的 bean 很可能不会与 Spring 管理的事务编织在一起。
关于java - 为什么在 Spring 中使用 Junit 运行时事务不会回滚,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43061798/