How to get the number of entries written to DB in Spring Batch? Code Answer

Hello Developer, Hope you guys are doing great. Today at Tutorial Guruji Official website, we are sharing the answer of How to get the number of entries written to DB in Spring Batch? without wasting too much if your time.

The question is published on by Tutorial Guruji team.

I have a JobExecutionListener that writes the job status after execution into a log file. How can I also get the number of items processed?

@Component
public class JobListener implements JobExecutionListener {
    @Override
    public void afterJob(JobExecution task) {
          log.info(task.getStatus());
          //number of entries??
    }
}

Answer

I see 2 ways to do it.

  1. You can implement the ItemProcessListener. This interface is called after/before an item is processed. This interface also reported any errors.

    public class ItemCountsListener implements ItemProcessListener<Object, Object> {
    
    private static final AtomicLong count = new AtomicLong(1);
    
    public void afterProcess(Object item, Object result) {
        count.getAndIncrement();
    }
    
    public void beforeProcess(Object item) {}
    public void onProcessError(Object item, Exception e) {  }
    

    }

  2. Or you can call the method jobExecution.getStepExecutions(). This method returns a Collection<StepExecution> object. In this class, there is a method getWriteCount which returns the current number of items written for this execution. I would do something similar to this code :

 public void afterJob(JobExecution jobExecution) {
         int nbItemsProcessed;
         for (StepExecution stepExecution : jobExecution.getStepExecutions()) {
            nbItemsProcessed += stepExecution.getWriteCount();
         }   
      }
We are here to answer your question about How to get the number of entries written to DB in Spring Batch? - If you find the proper solution, please don't forgot to share this with your team members.

Related Posts

Tutorial Guruji