org.fluentjdbc.DbContextSaveBuilder 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 org.fluentjdbc.util.ExceptionUtil;
import javax.annotation.CheckReturnValue;
import java.sql.Connection;
import java.sql.SQLException;
/**
* Generate INSERT
or UPDATE
statements on {@link DbContextTable} by
* collecting field names and parameters. Support autogeneration of primary keys and unique natural
* keys. Example:
*
*
* {@link DbContextTable} table = context.table("database_test_table");
* try (DbContextConnection ignored = context.startConnection(dataSource)) {
* DatabaseSaveResult<Long> result = table.newSaveBuilder("id", object.getId())
* .uniqueKey("name", object.getName())
* .setField("value", object.getValue())
* .execute();
* object.setId(result.getId());
* }
*
*
* @see DatabaseInsertBuilder
*/
public class DbContextSaveBuilder {
private final DbContextTable table;
private final DatabaseSaveBuilder saveBuilder;
public DbContextSaveBuilder(DbContextTable table, DatabaseSaveBuilder saveBuilder) {
this.table = table;
this.saveBuilder = saveBuilder;
}
/**
* Specify a natural key for this table. If the id
is null and there is a unique key
* match, UPDATE is called with this row and the existing primary key is returned, instead of INSERT.
* If more than one uniqueKey, fluent-jdbc assumes a composite unique constraint, that is all
* fields must match
*/
@CheckReturnValue
public DbContextSaveBuilder uniqueKey(String fieldName, Object fieldValue) {
//noinspection ResultOfMethodCallIgnored
saveBuilder.uniqueKey(fieldName, fieldValue);
return this;
}
/**
* Specify a column name to be saved
*/
@CheckReturnValue
public DbContextSaveBuilder setField(String fieldName, Object fieldValue) {
//noinspection ResultOfMethodCallIgnored
saveBuilder.setField(fieldName, fieldValue);
return this;
}
/**
* Executes the UPDATE
or INSERT
statement and returns a
* {@link DatabaseSaveResult} which explains what operation was executed.
* See {@link DatabaseSaveBuilder#execute(Connection)}
*/
public DatabaseSaveResult execute() {
return saveBuilder.execute(table.getConnection());
}
}
© 2015 - 2024 Weber Informatics LLC | Privacy Policy