org.fluentjdbc.DbContextBulkInsertBuilder 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 java.sql.PreparedStatement;
import java.util.List;
import java.util.function.Function;
/**
* Fluently generate a INSERT ...
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.
*
* Example:
*
*
* public void saveAll(List<TagType> tagTypes) {
* tagTypesTable.bulkInsert(tagTypes)
* .setField("name", TagType::getName)
* .execute();
* }
*
*/
public class DbContextBulkInsertBuilder implements DatabaseBulkUpdatable> {
private final DbContextTable table;
private final DatabaseBulkInsertBuilder builder;
public DbContextBulkInsertBuilder(DbContextTable table, DatabaseBulkInsertBuilder 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 insert
*/
@Override
public DbContextBulkInsertBuilder setField(String fieldName, Function transformer) {
//noinspection ResultOfMethodCallIgnored
builder.setField(fieldName, transformer);
return this;
}
/**
* Adds a list function that will be called for each object to get the value
* each of the corresponding parameters in the {@link PreparedStatement}
*/
@Override
public > DbContextBulkInsertBuilder setFields(List fields, Function values) {
//noinspection ResultOfMethodCallIgnored
builder.setFields(fields, values);
return this;
}
/**
* Executes INSERT INTO table ...
and calls {@link PreparedStatement#addBatch()} for
* each row
*
* @return the count of rows inserted
*/
public int execute() {
return builder.execute(table.getConnection());
}
}
© 2015 - 2024 Weber Informatics LLC | Privacy Policy