All Downloads are FREE. Search and download functionalities are using the official Maven repository.

org.fluentjdbc.DatabaseBulkDeleteBuilder Maven / Gradle / Ivy

package org.fluentjdbc;

import org.fluentjdbc.util.ExceptionUtil;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.function.Function;
import java.util.stream.IntStream;

import static org.fluentjdbc.DatabaseStatement.addBatch;

/**
 * Fluently generate a DELETE ... WHERE ... statement for a list of objects.
 * Create with a list of object and use {@link #where(String, Function)} to add a function
 * which will be called for each object to create the WHERE field = ? value.
 *
 * 

Example:

* *
 *     public void deleteAll(List<TagType> tagTypes, Connection connection) {
 *         tagTypesTable.bulkDelete(tagTypes)
 *              .where("id", TagType::getId)
 *              .execute(connection);
 *     }
 * 
*/ public class DatabaseBulkDeleteBuilder implements DatabaseBulkQueryable> { private final List whereConditions = new ArrayList<>(); private final List> whereParameters = new ArrayList<>(); private final DatabaseTable table; private final Iterable objects; public DatabaseBulkDeleteBuilder(DatabaseTable table, Iterable objects) { this.table = table; this.objects = objects; } /** * Adds a function that will be called for each object to get the value for * {@link PreparedStatement#setObject(int, Object)} for each row in the bulk update * to extract the values for the WHERE fieldName = ? clause */ @Override public DatabaseBulkDeleteBuilder where(String field, Function value) { whereConditions.add(field + " = ?"); whereParameters.add(value); return this; } /** * Executes DELETE FROM table WHERE field = ? AND ... * and calls {@link PreparedStatement#addBatch()} for each row * * @return the sum count of all the rows deleted */ public int execute(Connection connection) { String deleteStatement = "delete from " + table.getTableName() + " where " + String.join(" and ", whereConditions); try (PreparedStatement statement = connection.prepareStatement(deleteStatement)) { addBatch(statement, objects, whereParameters); int[] counts = statement.executeBatch(); return IntStream.of(counts).sum(); } catch (SQLException e) { throw ExceptionUtil.softenCheckedException(e); } } }




© 2015 - 2024 Weber Informatics LLC | Privacy Policy