org.fluentjdbc.DatabaseBulkUpdateBuilder Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of fluent-jdbc Show documentation
Show all versions of fluent-jdbc Show documentation
A Java library used to execute JDBC statements and build SQL
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;
public class DatabaseBulkUpdateBuilder extends DatabaseStatement
implements DatabaseBulkQueriable>, DatabaseBulkUpdateable> {
private final DatabaseTable table;
private final List objects;
private final List whereConditions = new ArrayList<>();
private final List> whereParameters = new ArrayList<>();
private final List updateFields = new ArrayList<>();
private final List> updateParameters = new ArrayList<>();
public DatabaseBulkUpdateBuilder(DatabaseTable table, List objects) {
this.table = table;
this.objects = objects;
}
@Override
public DatabaseBulkUpdateBuilder where(String field, Function value) {
whereConditions.add(field + " = ?");
whereParameters.add(value);
return this;
}
@Override
public DatabaseBulkUpdateBuilder setField(String fieldName, Function transformer) {
updateFields.add(fieldName);
updateParameters.add(transformer);
return this;
}
public int execute(Connection connection) {
String updateStatement = createUpdateStatement(table.getTableName(), updateFields, whereConditions);
try (PreparedStatement statement = connection.prepareStatement(updateStatement)) {
List> parameters = new ArrayList<>();
parameters.addAll(updateParameters);
parameters.addAll(whereParameters);
addBatch(statement, objects, parameters);
int[] counts = statement.executeBatch();
return IntStream.of(counts).sum();
} catch (SQLException e) {
throw ExceptionUtil.softenCheckedException(e);
}
}
}
© 2015 - 2025 Weber Informatics LLC | Privacy Policy