Reputation: 45
I am working with Spring Batch(using Spring boot). My requirement is to read data from db, process it(validations and stuffs) and write it to a file. I am trying to achieve this using a batch step.
Problem is, if i define a step, the reader,processor and writer should be having similar parameters.(from examples i saw and the error i got) Like if my reader is returning a db domain object, the processor and writer should be having domain object parameters.
What i am looking for is, reader should return domain object, processor should receive domain object and convert it to dto/pojo(after validations and data conversion) and return dto object. Writer should be receiving dto object and write it to file.
Please let me know if that is possible within a single batch step to have different kind of parameters. If so please give me any example/links to it.
Upvotes: 0
Views: 1378
Reputation: 31745
Transforming items is a typical use case of an item processor. Here is an excerpt from the ItemProcessor section of the docs:
An ItemProcessor is simple. Given one object, transform it and return another. The provided object may or may not be of the same type
So in your case, the reader can return domain objects which are transformed by an item processor to DTOs. The writer then will get DTOs and write them to the file. Here is a quick example that transforms numbers to strings:
@Bean
public ItemReader<Integer> itemReader() {
return new ListItemReader<>(Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10));
}
@Bean
public ItemProcessor<Integer, String> itemProcessor() {
return item -> "foo" + item;
}
@Bean
public ItemWriter<String> itemWriter() {
return items -> {
for (String item : items) {
System.out.println("item = " + item);
}
};
}
@Bean
public Step step() {
return stepBuilderFactory.get("step")
.<Integer, String>chunk(5)
.reader(itemReader())
.processor(itemProcessor())
.writer(itemWriter())
.build();
}
Upvotes: 1