简体   繁体   中英

How to execute multi batch delete in JdbcTemplate?

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

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

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM