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

org.fluentjdbc.DatabaseUpdateBuilder Maven / Gradle / Ivy

There is a newer version: 0.5.3
Show newest version
package org.fluentjdbc;

import javax.annotation.Nullable;
import javax.annotation.ParametersAreNonnullByDefault;
import java.sql.Connection;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

@ParametersAreNonnullByDefault
public class DatabaseUpdateBuilder extends DatabaseStatement implements DatabaseUpdateable {

    private final String tableName;
    private final List whereConditions = new ArrayList<>();
    private final List whereParameters = new ArrayList<>();
    private final List updateFields = new ArrayList<>();
    private final List updateValues = new ArrayList<>();

    public DatabaseUpdateBuilder(String tableName) {
        this.tableName = tableName;
    }

    DatabaseUpdateBuilder setWhereFields(List whereConditions, List whereParameters) {
        this.whereConditions.addAll(whereConditions);
        this.whereParameters.addAll(whereParameters);
        return this;
    }

    @Override
    public DatabaseUpdateBuilder setFields(Collection fields, Collection values) {
        this.updateFields.addAll(fields);
        this.updateValues.addAll(values);
        return this;
    }

    @Override
    public DatabaseUpdateBuilder setField(String field, @Nullable Object value) {
        this.updateFields.add(field);
        this.updateValues.add(value);
        return this;
    }

    public int execute(Connection connection) {
        if (updateFields.isEmpty()) {
            return 0;
        }
        List parameters = new ArrayList<>();
        parameters.addAll(updateValues);
        parameters.addAll(whereParameters);
        return executeUpdate(createUpdateStatement(tableName, updateFields, whereConditions), parameters, connection);
    }

}