问题描述
spring我的项目的批处理,我只是尝试从csv文件中读取并使用JdbcBatchItemWriter作为编写器将数据加载到数据库。
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.
我知道我可以直接在sql语句中执行此操作,但这将特定于Mysql,但我希望我的代码与DBMS无关。
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.
这里是我的作者声明java config
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;
}
预先感谢您的帮助
推荐答案
这很简单:
编写自定义 ItemWriter<>
并在 write()
方法中执行插入操作和 - 如果重复 - 执行更新;检查dup键是否使用查找或重复的异常捕获。
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.
这篇关于使用JdbcBatchItemWriter更新重复键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!