Search code examples
javajpaspring-data-jpaspring-scheduled

Spring Data JPA not returning results in Scheduled task


I have an entity ExamEvent and corresponding repository ExamEventRepository. I am populating the repository in a service ExamEventService. Now, trying to access all the entities through ExamEventService (which inturn will call repository) in a scheduled task. But it is returning empty results. Strangely, if I query for all entities from ExamEventService from any other service it returns all results. It seems something missing in my scheduled task to access JPA. Any hints to what could be missing here ? Thanks.

ExamEventRepository.java

public interface ExamEventRepository extends JpaRepository<ExamEvent, Long>, JpaSpecificationExecutor<ExamEvent> {
    Optional<ExamEvent> findByRequestId(long requestId);
}

ExamEventService.java

@Service
@Slf4j
@Transactional
public class ExamEventService {

    @Autowired
    private ExamEventRepository examEventRepository;

    public List<ExamEvent> findAll() {
        return examEventRepository.findAll();
    }
...
}

SchedulerService.java

@Slf4j
@Service
@Transactional
public class SchedulerService {


    @Autowired
    private ExamEventRepository examEventRepository;


    @Scheduled(fixedDelayString = "${light.otp.schedule.delay-in-ms}")
    public void scheduledTask() {
        List<ExamEvent> search = examEventRepository.findAll();
        log.info("Events==>" + search); // This list is empty here.
     
    }

}

SchedulerConfig.java


@Configuration
@EnableScheduling
@EnableAsync
public class SchedulerConfig {


}

Log

Here, some other service is able to get the results in main thread.

021-02-08 05:30:36.755  INFO 1774 --- [           main] c.light.request.service.RequestService   : Events==> [ExamEvent(id=3, scribeId=1, candidateId=1, requestId=2, otpGenerated=false, examSchedule=ExamSchedule(id=1, start=2021-02-08T00:30:36.409603Z, end=2021-02-08T02:30:36.409603Z))]
2021-02-08 05:30:41.437  INFO 1774 --- [   scheduling-1] com.light.scheduler.SchedulerService     : Events==> []

Another observation is that, after saving ExamEvent into repository, its not actually reflecting in H2 DB. I tried with save and flush but still its not visible in DB. The case when data is retrieved, it seem to have got it through in-memory. But in scheduler service it is trying to access DB where data doesn't exist.


Solution

  • Finally I found the root cause of the issue. It was happening since corresponding unit test was marked @Transactional. Hence, saved data was not flushed to DB and it was not accessible in scheduler thread. After I removed @Transactional from unit test, saved data is flushed and it is accessible from other threads.