Search code examples
spring-bootspring-data-jpaspring-transactionsspring-events

Entities are not fetching in Transaction event listener spring boot


I have a service call which is annotated with @Transactional which save some entities using spring data JPA.

@Override
@Async("tenant")
@Transactional
public List<TestDAO> testCreate(List<TestDAO> daos) {
  List<Test> converted = convert(daos);
  repository.save(converted);   
}

After save pushing an event using applicationEventPublisher.publishEvent(object);.

There is a transaction listener where I used to call and update above saved entities using service calls. Get call works perfectly, but update fails saying entity not found.

@TransactionalEventListener(value = Event.class, phase = TransactionPhase.AFTER_COMMIT)
public void onApplicationEvent(Event event) {
   Long id = event.getProcessId();
   //calling previously saved data. Works perfectly.
   List<TestDAO> daos=  testDAOServive.getItemByProcessID(id);              
   ExecutorService executorService = Executors.newFixedThreadPool(20);
   daos.forEach(testDao -> {
     Runnable task = () -> {
        testDao.setStatus("IN_PROGRESS");
        // Getting exception here.
        testDAOServive.updateItem(testDao);             
     }
   }
}

I tried making all the method as transactional. tried transaction after completion . I have removed Executor service then its working. Seems same transaction not getting carryforward in threads.


Solution

  • Added @Transactional on event listening method and its working now.

     **@Transactional**
        public void onApplicationEvent(Event event) {
       Long id = event.getProcessId();
       //calling previously saved data. Works perfectly.
       List<TestDAO> daos=  testDAOServive.getItemByProcessID(id);              
       ExecutorService executorService = Executors.newFixedThreadPool(20);
       daos.forEach(testDao -> {
         Runnable task = () -> {
            testDao.setStatus("IN_PROGRESS");
            // Getting exception here.
            testDAOServive.updateItem(testDao);             
         }
       }
    }