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 java.sql.Connection;
import java.util.ArrayList;
import java.util.List;

import javax.annotation.Nullable;
import javax.annotation.ParametersAreNonnullByDefault;

@ParametersAreNonnullByDefault
public class DatabaseUpdateBuilder extends DatabaseStatement {

    private final DatabaseTable table;
    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(DatabaseTable table) {
        this.table = table;
    }

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

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

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

    public void execute(Connection connection) {
        List parameters = new ArrayList<>();
        parameters.addAll(updateValues);
        parameters.addAll(whereParameters);
        executeUpdate(createUpdateStatement(), parameters, connection);
    }

    private String createUpdateStatement() {
        return "update " + table.getTableName()
            + " set " + join(",", updates(updateFields))
            + (whereParameters.isEmpty() ? "" : " where " + join(" and ", whereConditions));
    }

    private static List updates(List columns) {
        List result = new ArrayList<>();
        for (String column : columns) {
            result.add(column + " = ?");
        }
        return result;
    }



}