java - 为什么在 Spring 中使用 Junit 运行时事务不会回滚

标签 java spring hibernate junit

我正在尝试使用带有 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/

相关文章:

Java 将映射序列化到文件

java - org.hibernate.AssertionFailure : possible non-threadsafe access to the session

java - 让 Spring Boot 重新创建测试数据库

java - Spring、Hibernate、MVC 错误

具有约束违反异常的 hibernate 批量更新

java - 一个数组是另一个数组的子集

java - 枚举的 JPA 映射集合

java - 二维数组问题Java

java - 2腿(客户端凭据)oauth2服务器的 Spring 安全上下文设置

java - Spring 数据存储库将 null 作为 bytea 发送到 PostgreSQL 数据库