There is scenario where we want to load data from DB to DB . But we want to check if data is already present in target system then update it otherwise insert it into DB.
We are using below approach:
@Bean
ItemWriter<Student> onosItemWriter1() {
JdbcBatchItemWriter<Student> databaseItemWriter = new JdbcBatchItemWriter<>();
databaseItemWriter.setDataSource(dataSource);
databaseItemWriter.setJdbcTemplate(namedParameterJdbcTemplate);
databaseItemWriter.setSql(INSERT_QUERY);
ItemPreparedStatementSetter<Student> valueSetter = new ItemPreparedStatementSetter<Student>() {
@Override
public void setValues(Student student, PreparedStatement statement) throws SQLException {
if (Student.getId() < 0) {
log.info("Inserting!");
databaseItemWriter.setSql(INSERT_QUERY);
statement.setString(1, student.getName());
statement.setString(2, student.getEmail());
} else {
log.info("updateing!!!!");
databaseItemWriter.setSql(UPDATE_QUERY);
statement.setString(1, student.getName());
statement.setString(2, student.getEmail());
}
}
};
databaseItemWriter.setItemPreparedStatementSetter(valueSetter);
return databaseItemWriter;
}
above its working only for insert. How I can do it with one JDBC batch Item writer to update it as well dynamically. if record is already present in chunks.
The code you shared won't work, because you are configuring the query on the item writer based on a runtime information from the item itself (
Student.getId() < 0
).I would keep it simple and write a custom item writer like follows: