I have extended the batch service code provided by Official Spring-Batch site - Batch Processing Service and modified the ItemWriter to generate the CSV and to write to the database.
I have used CompositeItemWriter to write in both CSV and Database. However the JdbcBatchItemWriter is not working correctly with CompositeItemWriter. The code is shown below.
@Bean
public ItemWriter<Person> writer(DataSource dataSource) {
CompositeItemWriter<Person> cWriter = new CompositeItemWriter<Person>();
// For DataBase
JdbcBatchItemWriter<Person> writer = new JdbcBatchItemWriter<Person>();
writer.setItemSqlParameterSourceProvider(new BeanPropertyItemSqlParameterSourceProvider<Person>());
writer.setSql("INSERT INTO people (first_name, last_name) VALUES (:firstName, :lastName)");
writer.setDataSource(dataSource);
// For CSV
FlatFileItemWriter<Person> csvWriter = new FlatFileItemWriter<Person>();
csvWriter.setResource(new FileSystemResource(new File("./csv/new-data.csv")));
csvWriter.setShouldDeleteIfExists(true);
DelimitedLineAggregator<Person> lineAggregator = new DelimitedLineAggregator<Person>();
lineAggregator.setDelimiter(",");
BeanWrapperFieldExtractor<Person> fieldExtractor = new BeanWrapperFieldExtractor<Person>();
String[] names = {"firstName", "lastName"};
fieldExtractor.setNames(names);
lineAggregator.setFieldExtractor(fieldExtractor);
csvWriter.setLineAggregator(lineAggregator);
List<ItemWriter<? super Person>> mWriter = new ArrayList<ItemWriter<? super Person>>();
mWriter.add(writer); // **Comment this line and the code works fine**
mWriter.add(csvWriter);
cWriter.setDelegates(mWriter);
return cWriter;
}
Comment this line - mWriter.add(writer); to run the code. This shows that CompositeItemWriter is working good with FlatFileitemWriter, but not with JdbcBatchItemWriter. The error I am getting is -
or.springframework.jdbc.BadSqlGrammerException: PreparedStatementCallback; bad SQL grammar
[insert into people(first_name, last_name) VALUES (:firstName, :lastName)]
Caused by: Syntax error in SQl statement "insert into people((first_name, last_name) VALUES (:[*]firstName, :lastName)"; expected"), DEFAULT, NOT, EXISTS, INTERSECTS, SELECT, FROM"; SQL Statement:
How can I resolve JdbcBatchItemWriter to work correctly with CompositeItemWriter ?