问题
spring Batch for my project, and I'm simply trying to read from a csv file and load data to a database, using JdbcBatchItemWriter as writer.
I'm looking for a way to tell the writer to insert a new row, but, on duplicate key (or duplicate unique identifier) update row instead of failing.
I know I can do that directly in the sql statement, but that would be specific to Mysql, though I want my code to be DBMS-independent.
here is my writer declaration in the java config
@Bean
@StepScope
public ItemWriter<Person> writerHeadingCollectionsToDb(DataSource datasource) {
String sqlStatement = "INSERT INTO abcd(id, first_name, last_name, phone_number"
+ "VALUES (:id, :firstName, :lastName, :phoneNumber)";
JdbcBatchItemWriter<Person> itemWriter = new JdbcBatchItemWriter<Person>();
itemWriter.setSql(sqlStatement );
itemWriter.setDataSource(dataSource);
itemWriter.setItemSqlParameterSourceProvider(new BeanPropertyItemSqlParameterSourceProvider<Person>());
return itemWriter;
}
Thanks in advance for your help
回答1:
It's pretty easy:
Write a custom ItemWriter<>
and in write()
method do an insert and - if duplication - do an update; to check if dup key use a lookup or a duplicate exception catch.
来源:https://stackoverflow.com/questions/21532058/update-on-duplicate-key-with-jdbcbatchitemwriter