Spring4 @Scheduled @Transaction throws no transaction is in progress at flush for mutliple dataSources
I have resolved this issue by changing transactionManager configuration for the internal dataSource. It looks default transactionManager configured by @EnableTransactionManagement
is DataSourceTransactionManager and somehow begin() method on hibernate AbstractTransactionImpl isn't called, if job comes from any scheduler. So I change the DataSourceTransactionManager for internal dataSource to JpaTransactionManager like below. now all transactions for both dataSource go successfully whether the job comes from scheduler or UI. So I think my issue addressed on this post has been fixed
@Configuration
@EnableAutoConfiguration
@EnableScheduling
@EnableAsync
@EnableAspectJAutoProxy
@ComponentScan("com.my.client")
@EnableTransactionManagement
@EnableJpaRepositories(
entityManagerFactoryRef = "entityManagerFactory",
transactionManagerRef = "transactionManager",
basePackages = {"com.my.database.repository"})
public class ServerConfig extends SpringBootServletInitializer implements SchedulingConfigurer, AsyncConfigurer {
static Logger log = Logger.getLogger(ServerModeConfig.class.getName());
@Autowired
JpaVendorAdapter jpaVendorAdapter;
@Autowired
DataSource dataSource;
@Bean(name = "entityManager")
public EntityManager entityManager() {
return entityManagerFactory().createEntityManager();
}
@Primary
@Bean(name = "entityManagerFactory")
EntityManagerFactory entityManagerFactory() {
LocalContainerEntityManagerFactoryBean emf = new LocalContainerEntityManagerFactoryBean();
emf.setDataSource(dataSource);
emf.setJpaVendorAdapter(jpaVendorAdapter);
emf.setPackagesToScan("com.my.client.database.model");
emf.setPersistenceUnitName("default");
emf.afterPropertiesSet();
return emf.getObject();
}
@Bean(name = "transactionManager")
public PlatformTransactionManager transactionManager() {
JpaTransactionManager tm = new JpaTransactionManager();
tm.setEntityManagerFactory(entityManagerFactory());
return tm;
}
@Override
public void configureTasks(ScheduledTaskRegistrar taskRegistrar) {
taskRegistrar.setScheduler(taskExecutor());
}
/**
* get executor for scheduling job
* @return scheduled executor
*/
@Bean(destroyMethod="shutdown")
public Executor taskExecutor() {
return Executors.newScheduledThreadPool(20);
}
/**
* get executor for async job
* @return executor for asynchronous job but no time limit
*/
@Override
public Executor getAsyncExecutor() {
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
executor.setCorePoolSize(20);
executor.setMaxPoolSize(100);
executor.setQueueCapacity(200);
executor.initialize();
return executor;
}
@Override
public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {
return new MyClientAsyncExceptionHandler();
}
}
I had same probem with a @Transactional @Scheduled method. Making method public solved the problem. I don't no why!