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

org.fluentjdbc.DatabaseBulkUpdateBuilder Maven / Gradle / Ivy

There is a newer version: 0.5.3
Show newest version
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