Test Spring batch with @JpaDataTest

∥☆過路亽.° 提交于 2021-02-11 12:32:33

问题


I'm using spring batch 4.0 and i'm trying to test my batch. I would use embedded database h2 with @JpaDataTest but it doesn't work. When i add this annotation i got error

java.lang.IllegalStateException: Existing transaction detected in JobRepository. Please fix this and try again (e.g. remove @Transactional annotations from client).

@Transaction(propagation=Propagation.NEW_REQUIRED) on the @Test dosen't work.

I tried to copy every annotations from @JpaDataTest and remove @Transaction

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

But when i'm doing this, i'm lossing the EntityManager...

Someone already find a solution ?


回答1:


java.lang.IllegalStateException: Existing transaction detected in JobRepository. Please fix this and try again (e.g. remove @Transactional annotations from client).

This error happens when you try to run Spring Batch code (which drives a transaction) in an outer transactional context (the test in your example).

Instead of adding @Transaction(propagation=Propagation.NEW_REQUIRED) on the test, you should try to deactivate transactions instead, letting Spring Batch drive the transaction. For example, using:

@Transaction(propagation = Propagation.NOT_SUPPORTED)

I tried to copy every annotations from @JpaDataTest and remove @Transaction [...] But when i'm doing this, i'm lossing the EntityManager...

You need to make sure that Spring Batch uses the transaction manager you want (I guess a JpaTransactionManager in your case) to drive its transactions. To do that, you need to define a bean of type BatchConfigurer in your batch configuration and override getTransactionManager. Here is an example:

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

You can find more details in the Java Configuration section of the reference documentation.

Hope this helps.



来源:https://stackoverflow.com/questions/54979533/test-spring-batch-with-jpadatatest

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!