public class DbTransaction extends Object implements DbQueryable, AutoCloseable
MySQL, PostgreSQL and SQL Server are supported.
An object is created with the JDBC URL to the database. There is no factory for this type of object, simply store the string JDBC URL as opposed to a DbConnectionFactory.
The following facilities are provided (i.e. these are the reasons why objects of this class might be preferred over simply using JDBC directly):
execute(java.lang.String, java.lang.Object...) method prepares statements and does parameter substitution in one line.
query(java.lang.String, java.lang.Object...) method acts like execute, but returns an Iterable of objects representing rows.
This is more convenient for the java "for" statement than the JDBC ResultSet object.
java.util.Date,
LocalDate, etc.
insert(java.lang.String, java.util.Map<java.lang.String, ?>) and update(java.lang.String, java.util.Map<java.lang.String, ?>, java.lang.String, java.lang.Object...) take Maps of columns as arguments (easier than maintaining SQL strings)
insertAndFetchNewId(java.lang.String, java.util.Map<java.lang.String, ?>) performs an insert and returns the new "auto-increment ID".
insertIgnoringUniqueConstraintViolations(java.lang.String, java.util.Map<java.lang.String, ?>) and updateIgnoringUniqueConstraintViolations(java.lang.String, java.util.Map<java.lang.String, ?>, java.lang.String, java.lang.Object...)
perform inserts and updates, but ignore any unique constraint violations.
For example using the "insert then update" pattern, for "just-in-time" creating records, can use these methods.
attempt(Runnable) establishes a savepoint before the runnable and rolls back to it on failure,
necessary for any operation that may fail when using PostgreSQL.DbTransaction.RollbackListener objects with addRollbackListener(RollbackListener).
When the transaction rolls back, this listener will get called.
This is so that any primary keys which have been assigned and stored in Java objects,
which are now no longer valid due to the rollback, may be removed from the Java objects.
Upon creating an object, a connection is made to the database, and a transaction is started.
Upon executing commit() or rollback() the connection is closed.
Although opening a connection each time is not as efficient as using a connection pool, this class is extremely simple,
which has advantages both in terms or reliability, maintainability and also speed. (For example, C3P0 has > 50 KLOC).
Opening a connection to MySQL is fast.
DbTransaction objects are not thread safe; do not use them from multiple threads simultaneously.
Example usage:
String jdbc = "jdbc:mysql://hostname/dbName?user=x&password=x&useUnicode=true&characterEncoding=UTF-8";
try (DbTransaction db = new DbTransaction(jdbc)) {
db.execute("DELETE FROM x WHERE id=?", 9);
db.commit();
}
| Modifier and Type | Class and Description |
|---|---|
static class |
DbTransaction.CannotConnectToDatabaseException |
static class |
DbTransaction.DbQueryResultRow |
static class |
DbTransaction.DbQueryResultRowIterator |
static class |
DbTransaction.DbQueryResultSet |
static class |
DbTransaction.DbServerProduct |
static interface |
DbTransaction.DbTransactionFactory |
static class |
DbTransaction.ForeignKeyConstraintViolation |
static interface |
DbTransaction.RollbackListener |
static class |
DbTransaction.SqlException |
static class |
DbTransaction.UniqueConstraintViolation |
| Modifier and Type | Field and Description |
|---|---|
protected Connection |
connection |
protected Map<Class<? extends Enum<?>>,String> |
postgresTypeForEnum |
protected Map<String,PreparedStatement> |
preparedStatements |
DbTransaction.DbServerProduct |
product |
protected List<DbTransaction.RollbackListener> |
rollbackListeners |
| Constructor and Description |
|---|
DbTransaction(String jdbcUrl) |
| Modifier and Type | Method and Description |
|---|---|
void |
addPostgresTypeForEnum(Class<? extends Enum<?>> enumClass,
String postgresType) |
void |
addRollbackListener(DbTransaction.RollbackListener listener)
For example, during insert in jOOQ:
|
<V> void |
appendIn(Appendable sql,
List<? super V> sqlParams,
String field,
Collection<? extends V> values)
Writes "foo IN (?,?,?)"
|
protected void |
appendInsertStatement(StringBuilder sql,
List<Object> params,
String table,
Map<String,?> cols) |
protected void |
appendSetClauses(StringBuilder sql,
List<Object> params,
Map<String,?> cols) |
void |
attempt(Runnable r)
Sets a savepoint as is necessary on PostgreSQL, runs the code,
then rolls back to the savepoint on RuntimeException or discards the savepoint on success.
|
void |
close() |
protected void |
closeConnection() |
void |
commit() |
void |
deleteOrThrowForeignKeyConstraintViolation(String table,
String where,
Object... args)
For normal delete where you don't expect a possible foreign key constraint violation, use
execute(String, Object...) instead |
void |
execute(CharSequence sql,
List<?> args) |
void |
execute(String sql,
Object... args) |
protected long |
fetchNewPkValue() |
protected Connection |
getConnection() |
String |
getFromDual() |
protected PreparedStatement |
getPreparedStatement(String sql) |
protected String |
getQuestionMarkForValue(Object value) |
String |
getSchemaQuote() |
static String |
getSqlForLog(String sql,
Object[] args) |
void |
insert(String table,
Map<String,?> cols) |
void |
insert(org.jooq.TableRecord<?> record) |
long |
insertAndFetchNewId(String table,
Map<String,?> cols) |
long |
insertAndFetchNewIdOrThrowUniqueConstraintViolation(String table,
Map<String,?> cols) |
void |
insertIgnoringUniqueConstraintViolations(String table,
Map<String,?> cols) |
void |
insertOrThrowUniqueConstraintViolation(String table,
Map<String,?> cols) |
void |
insertOrUpdate(String table,
Map<String,?> colsToUpdate,
Map<String,?> colsToInsert,
String... primaryKeyColumns)
Inserts (colsToInsert + colsToUpdate) and, if that fails because the row already exists,
updates (colsToUpdate) where (primaryKeyColumns out of colsToInsert).
|
protected PreparedStatement |
insertParamsToPreparedStatement(String sql,
Object... args) |
static boolean |
isForeignKeyConstraintViolation(String msg) |
org.jooq.DSLContext |
jooq() |
protected void |
logNewTransaction() |
static String |
parseUniqueConstraintViolationOrNull(String msg) |
DbTransaction.DbQueryResultSet |
query(CharSequence sql,
List<?> args) |
DbTransaction.DbQueryResultSet |
query(String sql,
Object... args) |
void |
rollback() |
void |
rollbackIfConnectionStillOpen() |
protected void |
rollbackToSavepointAndThrowConstraintViolation(Savepoint initialState,
RuntimeException exception)
If "exception" represents a violation exception it is thrown and the connection is rolled back to "initialState",
otherwise the original exception is re-thrown.
|
void |
update(String table,
Map<String,?> cols,
String where,
Object... whereParams) |
void |
updateIgnoringUniqueConstraintViolations(String table,
Map<String,?> cols,
String where,
Object... whereParams) |
void |
updateOrThrowUniqueConstraintViolation(String table,
Map<String,?> cols,
String where,
Object... whereParams) |
public final DbTransaction.DbServerProduct product
protected Connection connection
protected final List<DbTransaction.RollbackListener> rollbackListeners
protected final Map<String,PreparedStatement> preparedStatements
public DbTransaction(String jdbcUrl) throws DbTransaction.CannotConnectToDatabaseException
public void close()
close in interface AutoCloseableprotected void logNewTransaction()
protected Connection getConnection()
protected PreparedStatement getPreparedStatement(String sql)
protected PreparedStatement insertParamsToPreparedStatement(String sql, Object... args)
protected long fetchNewPkValue()
public static String parseUniqueConstraintViolationOrNull(String msg)
public static boolean isForeignKeyConstraintViolation(String msg)
protected void rollbackToSavepointAndThrowConstraintViolation(Savepoint initialState, RuntimeException exception) throws DbTransaction.UniqueConstraintViolation, DbTransaction.ForeignKeyConstraintViolation
protected void closeConnection()
public void addPostgresTypeForEnum(Class<? extends Enum<?>> enumClass, String postgresType)
public void addRollbackListener(DbTransaction.RollbackListener listener)
db.addRollbackListener(() -> {
venue.setVid(null);
venue.changed(VENUES.VID, false);
} );
public org.jooq.DSLContext jooq()
public DbTransaction.DbQueryResultSet query(String sql, Object... args)
query in interface DbQueryablepublic DbTransaction.DbQueryResultSet query(CharSequence sql, List<?> args)
query in interface DbQueryablepublic void execute(String sql, Object... args) throws DbTransaction.SqlException
DbTransaction.SqlExceptionpublic void attempt(Runnable r)
public void deleteOrThrowForeignKeyConstraintViolation(String table, String where, Object... args) throws DbTransaction.ForeignKeyConstraintViolation
execute(String, Object...) insteadpublic void execute(CharSequence sql, List<?> args)
protected void appendSetClauses(StringBuilder sql, List<Object> params, Map<String,?> cols)
protected void appendInsertStatement(StringBuilder sql, List<Object> params, String table, Map<String,?> cols)
public void insert(org.jooq.TableRecord<?> record)
public void insertOrThrowUniqueConstraintViolation(String table, Map<String,?> cols) throws DbTransaction.UniqueConstraintViolation
public void insertIgnoringUniqueConstraintViolations(String table, Map<String,?> cols)
public long insertAndFetchNewIdOrThrowUniqueConstraintViolation(String table, Map<String,?> cols) throws DbTransaction.UniqueConstraintViolation
public void updateOrThrowUniqueConstraintViolation(String table, Map<String,?> cols, String where, Object... whereParams) throws DbTransaction.UniqueConstraintViolation
public void updateIgnoringUniqueConstraintViolations(String table, Map<String,?> cols, String where, Object... whereParams)
public void insertOrUpdate(String table, Map<String,?> colsToUpdate, Map<String,?> colsToInsert, String... primaryKeyColumns)
public void rollback()
public void commit()
public void rollbackIfConnectionStillOpen()
public String getFromDual()
public String getSchemaQuote()
public <V> void appendIn(Appendable sql, List<? super V> sqlParams, String field, Collection<? extends V> values)
Copyright © 2003–2018. All rights reserved.