【问题标题】:javax.persistence.TransactionRequiredException in Spring Boot integration testSpring Boot 集成测试中的 javax.persistence.TransactionRequiredException
【发布时间】:2019-02-18 13:30:29
【问题描述】:

我有一个 Spring Boot 2 应用程序,其中有一个 JdbcPersistenceHelper,如下所示:

@Component
public class JdbcPersistenceHelper {

    private EntityManager entityManager;

    @Autowired
    public JdbcPersistenceHelper(EntityManager entityManager) {
        this.entityManager = entityManager;
    }

    // Some persistence-related utility methods here

我正在使用这个类从我的测试中生成一些夹具数据,并且我有几个 @DataJpaTest 注释测试成功使用它。但是,当我尝试在集成测试(@SpringBootTest 带注释的测试类)中使用它时,出现以下错误:

javax.persistence.TransactionRequiredException:执行更新/删除查询

我的集成测试如下所示:

@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.MOCK, classes = ExchangeRateStoreApplication.class)
@AutoConfigureMockMvc
public class GenerateStrategyRatesTest {
    @Autowired
    MockMvc mockMvc;

    @Autowired
    EntityManager entityManager;

    @Autowired
    JdbcPersistenceHelper jdbcPersistenceHelper;

    @BeforeEach
    void setUp() {
        jdbcPersistenceHelper.persistAllUpdatingStrategiesAvailable();
        jdbcPersistenceHelper.persistAllExchangeRateProvidersAvailable();
    }

    // Some test methods here

目前,我正在使用 H2 内存数据库,我的 Spring Boot 的 application.yaml 如下所示:

spring:
  datasource:
    driver-class-name: org.h2.Driver
    url: jdbc:h2:mem:ExchangeRateDB;DB_CLOSE_DELAY=-1
    username: err
  jpa:
    database-platform: org.hibernate.dialect.H2Dialect

我错过了什么吗?

【问题讨论】:

    标签: java spring spring-boot spring-data-jpa


    【解决方案1】:

    将您的测试类或之前的方法标记为绑定到事务:

    @BeforeEach
    @Transactional
    void setUp() {
    

    @SpringBootTest
    @Transactional
    @AutoConfigureMockMvc
    public class GenerateStrategyRatesTest
    

    如果没有正在运行的事务,您将无法执行持久/更新/删除操作。

    【讨论】:

      猜你喜欢
      • 2020-02-25
      • 1970-01-01
      • 1970-01-01
      • 2015-08-20
      • 2020-04-24
      • 2017-10-27
      • 1970-01-01
      • 2019-07-06
      • 2017-06-28
      相关资源
      最近更新 更多