【问题标题】:Test Spring batch with @JpaDataTest使用 @JpaDataTest 测试 Spring 批处理
【发布时间】:2019-03-04 08:44:29
【问题描述】:

我正在使用 Spring Batch 4.0,并且正在尝试测试我的批次。 我会将嵌入式数据库 h2 与 @JpaDataTest 一起使用,但它不起作用。 当我添加此注释时出现错误

java.lang.IllegalStateException:在 JobRepository 中检测到现有事务。请修复此问题并重试(例如,从客户端删除 @Transactional 注释)。

@Test 上的@Transaction(propagation=Propagation.NEW_REQUIRED) 不起作用。

我试图从@JpaDataTest 复制每个注释并删除@Transaction

@BootstrapWith(SpringBootTestContextBootstrapper.class)
@OverrideAutoConfiguration(enabled = false)
@AutoConfigureCache
@AutoConfigureDataJpa
@AutoConfigureTestDatabase
@AutoConfigureTestEntityManager
@ImportAutoConfiguration

但是当我这样做时,我失去了 EntityManager...

有人已经找到解决方案了吗?

【问题讨论】:

  • 如果你用@Transactional(propagation = NOT_SUPPORTED)注释你的@DataJpaTest(假设你的意思是不是@JpaDataTest)类会发生什么?

标签: spring spring-data-jpa spring-batch spring-test


【解决方案1】:

java.lang.IllegalStateException:在 JobRepository 中检测到现有事务。请修复此问题并重试(例如,从客户端删除 @Transactional 注释)。

当您尝试在外部事务上下文(示例中的测试)中运行 Spring Batch 代码(驱动事务)时会发生此错误。

您应该尝试停用事务,而不是在测试中添加@Transaction(propagation=Propagation.NEW_REQUIRED),而是让 Spring Batch 驱动事务。例如,使用:

@Transaction(propagation = Propagation.NOT_SUPPORTED)

我试图从 @JpaDataTest 复制每个注释并删除 @Transaction [...] 但是当我这样做时,我丢失了 EntityManager...

您需要确保 Spring Batch 使用您想要的事务管理器(我猜在您的情况下是 JpaTransactionManager)来驱动其事务。为此,您需要在批处理配置中定义BatchConfigurer 类型的bean 并覆盖getTransactionManager。这是一个例子:

@Bean
public BatchConfigurer batchConfigurer() {
    return new DefaultBatchConfigurer() {
            @Override
            public PlatformTransactionManager getTransactionManager() {
                    return new MyTransactionManager();
            }
    };
}

您可以在参考文档的Java Configuration 部分找到更多详细信息。

希望这会有所帮助。

【讨论】:

    猜你喜欢
    • 2018-05-22
    • 2018-03-08
    • 1970-01-01
    • 1970-01-01
    • 2017-10-28
    • 1970-01-01
    • 2016-03-04
    • 1970-01-01
    • 2019-07-26
    相关资源
    最近更新 更多