How to execute multi batch delete in JdbcTemplate?

最后都变了- 提交于 2019-12-10 23:24:14

问题


I want to delete multiple database entries at once. Each entry should only be deleted if 3 fields match (here: name, email, age).

If I'd just wanted to delete by a single property, I'd go for:

String sql = "DELETE FROM persons WHERE (email) IN (?)";

JdbcTemplate template;
template.execute(sql, Arrays.asList(emails...));

But what if my condition is formed by multiple fields?

String sql = "DELETE FROM persons WHERE (name, email, age) IN (?, ?, ?)";

JdbcTemplate template;
template.execute(sql, ...); ???

The condition should always match all 3 fields (AND)!


回答1:


Use the batchUpdate(sql, batchArgs, argTypes) method.

String sql = "DELETE FROM persons WHERE name = ? AND email = ? AND age = ?";
int[] argTypes = { Types.VARCHAR, Types.VARCHAR, Types.INTEGER };

List<Object[]> batchArgs = new ArrayList<>();
batchArgs.add(new Object[] { "John Doe", "john@example.com", 42 });
batchArgs.add(new Object[] { "Jane Smith", "jane@example.com", 47 });
. . .

JdbcTemplate template = ...;
int[] rowCounts = template.batchUpdate(sql, batchArgs, argTypes);



回答2:


A batchUpdate is what you are looking for here. You would need to change/tweak your query a little bit though.

If you can pass a list of objects (you must match the class members with the values on the SQL query), it can be done automatically:

private final NamedParameterJdbcTemplate namedParameterJdbcTemplate;

// class People { String name; String email; Integer age; }
final String sql = "DELETE FROM persons WHERE name = :name AND email = :email AND age = :age";
final SqlParameterSource[] batchArgs = SqlParameterSourceUtils.createBatch(people.toArray()); // List<People>
final int[] results = namedParameterJdbcTemplate.batchUpdate(sql, batchArgs);
logger.debug("{} record(s) inserted successfully", results.length);

The other approach would be what @Andreas proposed.


I would also recommend to use, always, parameterized queries: DELETE FROM persons WHERE name = :name AND email = :email AND age = :age.



来源:https://stackoverflow.com/questions/50471046/how-to-execute-multi-batch-delete-in-jdbctemplate

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