I have simple Spring-Service that (among other tasks) starts a spring batch job with the following code:
@Autowired
private JobRegistry jobRegistry;
@Autowired
private JobLauncher jobLauncher;
public void startMyJob() {
Job job = jobRegistry.getJob("myJobName");
JobParameters jobParameters = new JobParametersBuilder().toJobParameters();
jobLauncher.run(job, jobParameters);
}
This works fine, as long as there is no transaction active when the Serivce-Method is called. However, with an active transaction, I get this exception:
Caused by: java.lang.IllegalStateException: Existing transaction detected in JobRepository. Please fix this and try again (e.g. remove @Transactional annotations from client).
I cannot easily remove the existing transaction, since it is implied due to some framework code that is not within my reach.
So, how can I start the job anyway within this context? The new job just should not use the existing transaction. It could just start its own transaction - but how to configure it to make it work?
Use AbstractJobRepositoryFactoryBean.ValidateTransactionState
, but use carefully (Warning: Dragons ahead).
To use another transaction you can inject a custom SimpleJobLauncher.executor
with method Executor.run
marked as @Transactional() (or create a custom JobLauncher
and do the same trick on method run
).
I haven't tried because I haven't faced the problem, but hope can help.