How to return List of Entity from RepositoryItemReader rather than Entity Spring Batch

Viewed 274

I am using RepositoryItemReader as reader. I have requirement to process whole List of reader value for that chunk together.

When I am trying to do Chunk Processing by Extending Reader to return List, in my Processor I get error

class Car cannot be cast to java.util.list(Car is in unnamed module of loader 'app'; java.util.List is in module java.base of loader 'bootstrap')

Reader

 public class CarReader extends RepositoryItemReader<List<Car>>{
    
   @Autowired
   CarRepository carRepository;

   public CarReader(){
    super();
    this.setPageSize(100);
    this.setSort(CarSort());
    this.setRepository(carRepository);
    this.setMethodName("findAll");
    return repositoryItemReader;
  }

Repository

public interface CarRepository extends PagingAndSortingRepository<Car,long>{
   Page<Car> findAll(Pageable pageable);
}

Processor

public class CarProcessor implements ItemProcessor<List<Car>,List<Car>>{
  @Override
  public List<Car> process(List<Car> cars){
    //prepare CarTransform
 }
}

Step

@Bean
public Step step1() {
    return this.stepBuilderFactory.get("step1")
                .<List<Car>, List<CarTransform>>chunk(100)
                .reader(carReader)
                .processor(carProcessor)
                .writer(carWriter)
                .build();
}
1 Answers

See this example: https://github.com/emalock3/spring-batch-example/blob/master/src/main/java/com/github/emalock3/spring/example/BatchConfiguration.java

I don't think you should be using Lists in your reader/processor/writer... Instead just use the Car and CarTransform classes.

Spring Batch will handle doing all the of the chunking based on the chunk size you have set. Based on your configuration, it should be handling 100 records at a time automatically.

The error I think your seeing is because the findAll method is returning a Page<Car> type instead of Page<List<Car>>.

Your step configuration should look like this instead:

@Bean
public Step step1() {
    return this.stepBuilderFactory.get("step1")
                .<Car, CarTransform>chunk(100)
                .reader(carReader)
                .processor(carProcessor)
                .writer(carWriter)
                .build();
}

Reader:

public class CarReader extends RepositoryItemReader<Car> {

    @Autowired
    CarRepository carRepository;

    public CarReader() {
        super();
        this.setPageSize(100);
        this.setSort(CarSort());
        this.setRepository(carRepository);
        this.setMethodName("findAll");
    }
}

Processor:

public class CarProcessor implements ItemProcessor<Car, CarTransform> {
    @Override
    public CarTransform process(Car car) {
        // prepare CarTransform
    }
}
Related