Search code examples
jpaspring-transactions

Repository.Save() inside scheduling is not working


I have a repository.save() method called inside a scheduler. But it is not saving anything to the database. Following is my scheduler

@Component
@Transactional
@Slf4j
public class WomConditionActionJob {


@Autowired
private Environment env;

@Autowired
private ECCRepository eCCRepository;

@Autowired
private WOCRepository wOCRepository;

@Autowired
private PSRepository pSRepository;


@Scheduled(fixedDelayString = "${wCATrigger.polling.frequency}", initialDelayString = "${wCATrigger.initial.delay}")
public void execute() {

    try {
            final PauseStatus pause = pSRepository.findByPSName(PSName.PAUSE);
            pauseCondition(pause,threshold);
    } catch (Exception e) {
        log.error("Exception Occured {}", e);
    }

}

private void pauseCondition(final PauseStatus pause, final Integer threshold) {
        WOTCondition wotCId = workOrderConditionRepository.findById(1).get();
        wotCId.setPauseStatus(pause);
        wotCId.setIsUserAction(Boolean.FALSE);
        workOrderConditionRepository.save(wotConditionbyId);
        conditionCount.setErrorCount(0);
        errorConditionCountRepository.save(conditionCount);
    }
}

I trying using saveAndFlush() but that time I got Following error

[pool-2-thread-1]|ERROR|[o.s.s.s.TaskUtils$LoggingErrorHandler.handleError(96)]|Unexpected error occurred in scheduled task. org.springframework.transaction.UnexpectedRollbackException: Transaction rolled back because it has been marked as rollback-only at org.springframework.transaction.support.AbstractPlatformTransactionManager.processRollback(AbstractPlatformTransactionManager.java:873) at org.springframework.transaction.support.AbstractPlatformTransactionManager.commit(AbstractPlatformTransactionManager.java:710)


Solution

  • Adding this solved my issue

        @Transactional(propagation=Propagation.REQUIRES_NEW)

    Example

    @Scheduled(cron = "0/5 * * * * *")
    @Transactional(propagation=Propagation.REQUIRES_NEW)
    @Override
    public void scheduleJob() {
                
      Message message = new Message();
      message.setMessageId(UUID.randomUUID().toString());
      message.setAccountId("accountId");
      message.setSent(2L);
      message.setFailed(2L);
      message.setDelivered(2L);
            
      // saves or update message_report table
      messageRepository.save(message);
                 
    }