Reputation: 17375
I have a file with records.
I have to develop a spring batch program which will read the file and DELETE the same records from the database table.
Is it possible to run delete query through ItemWriter ???
Upvotes: 1
Views: 23275
Reputation: 6630
Serkans answer is right, but there are some more possibilities for working with batch sql
code example with spring batch xml config and 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]);
}
}
}
Upvotes: 3
Reputation: 5619
There is no difference between update or delete operations, only the sql changes; so simple answer to your question will be yes. The following code fragment may help for basic needs assuming that you are deleting from the Book table.
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());
}
}
}
Upvotes: 1