update on duplicate key with JdbcBatchItemWriter

拟墨画扇 提交于 2020-01-02 08:55:12

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!