org.fluentjdbc.DbContextBulkUpdateBuilder 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 javax.annotation.Nonnull;
import java.sql.PreparedStatement;
import java.util.function.Function;
/**
* Fluently generate a UPDATE ...
statement for a list of objects. Create with a list of object
* and use {@link #setField(String, Function)} to pass in a function that will be called for each object
* in the list to create the SET field = ?
value and {@link #where(String, Function)}
* which will be called for each object to create the WHERE field = ?
value.
*
* Example:
*
*
* public void saveAll(List<TagType> tagTypes) {
* tagTypesTable.bulkUpdate(tagTypes)
* .where("id", TagType::getId)
* .setField("name", TagType::getName)
* .execute();
* }
*
*/
public class DbContextBulkUpdateBuilder implements
DatabaseBulkQueryable>, DatabaseBulkUpdatable> {
private final DbContextTable table;
private final DatabaseBulkUpdateBuilder builder;
public DbContextBulkUpdateBuilder(@Nonnull DbContextTable table, DatabaseBulkUpdateBuilder builder) {
this.table = table;
this.builder = builder;
}
/**
* Adds a function that will be called for each object to get the value for
* {@link PreparedStatement#setObject(int, Object)} for each row in the bulk update
* to extract the values for the WHERE fieldName = ?
clause
*/
@Override
public DbContextBulkUpdateBuilder where(String field, Function value) {
//noinspection ResultOfMethodCallIgnored
builder.where(field, value);
return this;
}
/**
* Adds a function that will be called for each object to get the value for
* {@link PreparedStatement#setObject(int, Object)} for each row in the bulk update
* to extract the values for the SET fieldName = ?
clause
*/
@Override
public DbContextBulkUpdateBuilder setField(String fieldName, Function transformer) {
//noinspection ResultOfMethodCallIgnored
builder.setField(fieldName, transformer);
return this;
}
/**
* Executes UPDATE table SET field = ?, ... WHERE field = ? AND ...
* and calls {@link PreparedStatement#addBatch()} for each row
*
* @return the count of rows that were updated
*/
public int execute() {
return builder.execute(table.getConnection());
}
}
© 2015 - 2024 Weber Informatics LLC | Privacy Policy