org.fluentjdbc.DbContext Maven / Gradle / Ivy
package org.fluentjdbc;
import org.fluentjdbc.util.ExceptionUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.annotation.CheckReturnValue;
import javax.annotation.Nonnull;
import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.List;
import java.util.Optional;
/**
* Provides a starting point for for context oriented database operation. Create one DbContext for your
* application and use {@link #table(String)} to create {@link DbContextTable} object for each table
* you manipulate. All database operations must be nested inside a call to {@link #startConnection(DataSource)}.
*
* Example
*
* DbContext context = new DbContext();
*
* {@link DbContextTable} table = context.table("database_test_table");
* DataSource dataSource = createDataSource();
*
* try (DbContextConnection ignored = context.startConnection(dataSource)) {
* Object id = table.insert()
* .setPrimaryKey("id", null)
* .setField("code", 1002)
* .setField("name", "insertTest")
* .execute();
*
* assertThat(table.where("name", "insertTest").orderBy("code").listLongs("code"))
* .contains(1002L);
* }
*
*
*/
public class DbContext {
private static final Logger logger = LoggerFactory.getLogger(DbContext.class);
private final DatabaseStatementFactory factory;
public DbContext() {
this(new DatabaseStatementFactory(DatabaseReporter.LOGGING_REPORTER));
}
public DbContext(DatabaseStatementFactory factory) {
this.factory = factory;
}
/**
* Build an arbitrary select statement, e.g.
* dbContext.select("max(age) as max_age").from("persons").where("name", "Johannes").singleLong("max_age")
*/
@CheckReturnValue
public DbContextSqlBuilder select(String... columns) {
return new DbContextSqlBuilder(this).select(columns);
}
/**
* Execute an arbitrary SQL statement, e.g.
* dbContext.select("select 1 as number from dual").singleLong("max_age")
or
* dbContext.select("update persons set full_name = first_name || ' ' || last_name").executeUpdate()
*/
@CheckReturnValue
public DbContextStatement statement(String statement, List