如何在JdbcTemplate中执行多批删除?

时间:2018-05-22 15:09:40

标签: java sql spring spring-jdbc

我想一次删除多个数据库条目。每个条目只有在3个字段匹配时才会被删除(此处:姓名,电子邮件,年龄)。

如果我只想删除一个属性,我会选择:

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

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

但如果我的病情是由多个领域组成的呢?

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

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

条件应始终匹配所有3个字段(AND)!

2 个答案:

答案 0 :(得分:5)

使用batchUpdate(sql, batchArgs, argTypes)方法。

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);

答案 1 :(得分:1)

您在这里寻找batchUpdate。您需要稍微更改/调整您的查询。

如果你可以传递一个对象列表(你必须使用SQL查询中的值匹配类成员),它可以自动完成:

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);

另一种方法是@Andreas proposed

我还建议使用始终参数化的查询:DELETE FROM persons WHERE name = :name AND email = :email AND age = :age