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.CheckReturnValue;
import javax.annotation.Nullable;
import javax.annotation.ParametersAreNonnullByDefault;
import java.sql.Connection;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;

/**
 * Generate UPDATE statements by collecting field names and parameters. Example:
 *
 * 
 * int count = table
 *      .where("id", id)
 *      .update()
 *      .setField("name", "Something")
 *      .setField("code", 102)
 *      .execute(connection);
 * 
*/ @ParametersAreNonnullByDefault public class DatabaseUpdateBuilder implements DatabaseUpdatable { private final DatabaseTable table; private final List updateFields = new ArrayList<>(); private final List updateValues = new ArrayList<>(); private DatabaseWhereBuilder whereClause; public DatabaseUpdateBuilder(DatabaseTable table) { this.table = table; } /** * Calls {@link #setField(String, Object)} for each fieldName and parameter */ @Override public DatabaseUpdateBuilder setFields(Collection fields, Collection values) { this.updateFields.addAll(fields); this.updateValues.addAll(values); return this; } /** * Adds fieldName to UPDATE ... SET fieldName = ? and parameter to the list of parameters */ @Override public DatabaseUpdateBuilder setField(String field, @Nullable Object value) { this.updateFields.add(field); this.updateValues.add(value); return this; } /** * Will generate UPDATE statements, set parameters and execute to database */ public int execute(Connection connection) { if (updateFields.isEmpty()) { return 0; } List parameters = new ArrayList<>(); parameters.addAll(updateValues); parameters.addAll(whereClause.getParameters()); return table.newStatement("UPDATE", createUpdateStatement(), parameters).executeUpdate(connection); } private String createUpdateStatement() { return "update " + table.getTableName() + " set " + updateFields.stream().map(column -> column + " = ?").collect(Collectors.joining(",")) + whereClause.whereClause(); } @CheckReturnValue public DatabaseUpdateBuilder where(DatabaseWhereBuilder whereClause) { this.whereClause = whereClause; return this; } }