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

org.fluentjdbc.DatabaseInsertBuilder 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 DatabaseInsertBuilder extends DatabaseStatement {

    private List fieldNames = new ArrayList<>();
    private List parameters = new ArrayList<>();
    private DatabaseTable table;

    public DatabaseInsertBuilder(DatabaseTable table) {
        this.table = table;
    }

    List getParameters() {
        return parameters;
    }

    public DatabaseInsertBuilder setField(String fieldName, @Nullable Object parameter) {
        this.fieldNames.add(fieldName);
        this.parameters.add(parameter);
        return this;
    }

    public DatabaseInsertBuilder setFields(List fieldNames, List parameters) {
        this.fieldNames.addAll(fieldNames);
        this.parameters.addAll(parameters);
        return this;
    }

    public void execute(Connection connection) {
        executeUpdate(createInsertStatement(), parameters, connection);
    }

    String createInsertStatement() {
        String query = "insert into " + table.getTableName() +
                " (" + join(",", fieldNames)
                + ") values ("
                + join(",", repeat("?", fieldNames.size())) + ")";
        return query;
    }

    // TODO: This doesn't work for Android when idValue is null
    public  DatabaseInsertWithPkBuilder setPrimaryKey(String idField, @Nullable T idValue) {
        if (idValue != null) {
            setField(idField, idValue);
        }
        return new DatabaseInsertWithPkBuilder<>(this, idValue);
    }

}