I am very new to the spring batch. Trying to create a simple example for myself to understand some of the basic batch-processing concepts. Currently, my spring application starts but unable to execute a simple job which is as follows
Adding the GitHub repo link below the code snippets. Do feel free to suggest any other improvements if you can. Thank you :)
public ItemReader<Student> jsonItemReader() {
return new JsonItemReaderBuilder<Student>()
.jsonObjectReader(new JacksonJsonObjectReader<>(Student.class))
.resource(new ClassPathResource("Students.json"))
.name("studentJsonItemReader")
.saveState(true)
.build();
}
public Step sampleStep(JobRepository jobRepository, PlatformTransactionManager transactionManager) {
return new StepBuilder("studentProcessor", jobRepository)
.<Student, Student>chunk(10, transactionManager)
.reader(jsonItemReader())
.writer(itemWriter())
.processor(studentProcessor)
.build();
}
@Bean
public Job sampleJob(JobRepository jobRepository, Step sampleJob) {
return new JobBuilder("sampleJob", jobRepository)
.start(sampleJob)
.build();
}
@Bean
public ItemWriter<Student> itemWriter() {
return new StudentWriter();
}
public class StudentWriter implements ItemWriter<Student> {
@Autowired
private StudentRespository studentRespository;
@Override
public void write(Chunk<? extends Student> chunk) throws Exception {
studentRespository.saveAll(chunk);
}
}
Github link : https://github.com/mohasink24/spring-batch
I checked your sample. A few things:
@EnableBatchProcessing
here. With Spring Boot 3, there is no need for that annotation, unless you want to take complete control over how Spring Batch is configured (see migration notes)return student
(after some processing, otherwise the processor is useless if it returns exactly the same input item).@Component
. You should have a warning from any decent IDE with Spring support on this. Otherwise, you can remove the @Autowired
annotation, add a constructor that accepts a StudentRepository
and inject the repository when you create the bean:@Bean
public ItemWriter<Student> itemWriter(StudentRepository studentRepository) {
return new StudentWriter(studentRepository);
}
Those are already some good starting points to fix before going further. If you still have the issue, please update the question and the code and I will try to follow up on this.