我有一个包含记录的文件。
我必须开发一个spring批处理程序,它将读取文件并从数据库表中删除相同的记录。
是否可以通过ItemWriter ???
运行删除查询答案 0 :(得分:3)
Serkans的回答是正确的,但是使用批处理sql还有更多的可能性
使用spring batch xml config和java code
的代码示例<bean id="itemWriter" class="org.springframework.batch.item.database.JdbcBatchItemWriter">
<property name="dataSource" ref="dataSource" />
<property name="sql">
<!-- Why CDATA?
because < etc. is not allowed for xml values
when you use < xml parser will work, but
now the sql won't because of the & spring assumes
a placeholder, see
- AbstractSqlPagingQueryProvider.init(...)
- JdbcParameterUtils.countParameterPlaceholders(...)
-->
<value>
<![CDATA[
DELETE FROM TEST
WHERE id = ?
and sub.id = ?
and ...
]]>
</value>
</property>
<property name="itemPreparedStatementSetter">
<bean class="...FieldSetItemPreparedStatementSetter" />
</property>
</bean>
/**
* Implementation for {@link ItemPreparedStatementSetter},
* sets the values from {@link FieldSet}.
*
*/
public class FieldSetItemPreparedStatementSetter implements ItemPreparedStatementSetter<FieldSet> {
/** {@inheritDoc} */
@Override
public void setValues(FieldSet item, PreparedStatement ps) throws SQLException {
for (int i = 0; i < item.getValues().length; i++) {
// PreparedStatements start with 1
ps.setObject(i + 1, item.getValues()[i]);
}
}
}
答案 1 :(得分:0)
更新或删除操作之间没有区别,只有sql更改;如此简单的答案你的问题将是肯定的。 假设您要从Book表中删除,以下代码片段可能有助于满足基本需求。
public class BookJdbcItemWriter implements ItemWriter<Book> {
private static final String DELETE_BOOK = "delete from Book where id = ?";
private JdbcTemplate jdbcTemplate;
public BookJdbcItemWriter(DataSource dataSource) {
this.jdbcTemplate = new JdbcTemplate(dataSource);
}
public void write(List<? extends Book> items) throws Exception {
for(Book item : items) {
int updated = jdbcTemplate.update(DELETE_BOOK,item.getId());
}
}
}