@Scheduled + Hibernate -> LazyInitializationException

Viewed 2507

I am under Spring Boot 2.0.5, using Spring Data JPA

I have a class such as this one (for the sake of understanding):

@Component
public class Synchronizer {

    @Autowired
    private MyService myService; 

    @Transactional
    public void synchronizeAuto() {
        List<MyTest> tests = myService.getTests();
        tests.get(0).getMyLazyObject().getName();
    }
}

The configuration is in here (there are other config files that I omitted):

@Configuration
@EnableAsync
@EnableScheduling
@EnableTransactionManagement
public class SpringAsyncConfiguration implements AsyncConfigurer, SchedulingConfigurer {

    @Autowired
    private AppConfigProperties appConfigProperties;

    @Autowired
    private Synchronizer synchronizer;

    @Override
    public Executor getAsyncExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setCorePoolSize(appConfigProperties.getThreadpoolCorePoolSize());
        executor.setMaxPoolSize(appConfigProperties.getThreadpoolMaxPoolSize());
        executor.setQueueCapacity(appConfigProperties.getThreadpoolQueueCapacity());
        executor.setThreadNamePrefix("threadPoolExecutor-");
        executor.initialize();
        return executor;
    }

    @Override
    public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {
        return new AsyncExceptionHandler();
    }

    @Override
    public void configureTasks(ScheduledTaskRegistrar taskRegistrar) {
        taskRegistrar.addCronTask(new Runnable() {

            @Override
            @Transactional
            public void run() {
                synchronizer.synchronizeAuto();
            }

        }, appConfigProperties.getCronExpression());
    }
}

The class MyService calls a Spring JPA repository to get all the "Test" instances

A "Test" instance has a lazy loading (MyLazyObject)

Anyway, everything works like a charm if I call the method from my controller.

When it is run from the scheduler, I get the following error:

org.hibernate.LazyInitializationException: failed to lazily initialize a collection of role: com.tinea.apix.service.model.entity.apim.APIManagerEntity.synchroHistory, could not initialize proxy - no Session

Any idea?

2 Answers

Due to the use of the configureTasks which is called at configuration time, the Syncronizer is created very early. So early that it isn't eligible for proxy creation/post processing anymore. Which in turn leads to, at least the task, to use an unproxied instance and not having @Transactional applied.

Instead you should use an @Scheduled annotation together with the cronString property to resolve it the same way as you do now.

@Scheduled(cron="@appConfigProperties.cronExpression")

The @ symbol in a SpEL expression indicates that a bean with the given name should be resolved.

@Scheduled(cron = "0 30 17 * * ?")

other wise we can use like this also

Related