问题
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