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

org.fluentjdbc.DbContextBulkInsertBuilder Maven / Gradle / Ivy

There is a newer version: 0.5.3
Show newest version
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