com.databasesandlife.util.jdbc.ReadOnlyReconnectingDbConnection Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of java-common Show documentation
Show all versions of java-common Show documentation
Utility classes developed at Adrian Smith Software (A.S.S.)
package com.databasesandlife.util.jdbc;
import com.databasesandlife.util.jdbc.DbTransaction.DbQueryResultRow;
import com.databasesandlife.util.jdbc.DbTransaction.DbQueryResultSet;
import com.databasesandlife.util.jdbc.DbTransaction.DbTransactionFactory;
import com.databasesandlife.util.jdbc.DbTransaction.SqlException;
import java.util.Iterator;
import java.util.List;
/**
* Read-only access to a database, which re-connects to the database if the connection is lost.
*
* Is thread-safe, you can use this from multiple threads
*
* It is assumed that the results of one query are read before the next one begins.
* Starting a new query can close the old database connection when reconnecting, meaning reads from previous queries
* might not work.
*
* @see com.databasesandlife.util.jdbc.DbTransaction
* @author This source is copyright Adrian Smith and licensed under the LGPL 3.
* @see Project on GitHub
*/
public class ReadOnlyReconnectingDbConnection implements DbQueryable {
protected DbTransactionFactory fac;
protected ThreadLocal tx = new ThreadLocal<>();
public ReadOnlyReconnectingDbConnection(DbTransactionFactory fac) {
this.fac = fac;
}
protected abstract class ReconnectingDbQueryResultSet extends DbQueryResultSet {
protected abstract DbQueryResultSet query();
@Override public Iterator iterator() {
if (tx.get() != null) {
try { return query().iterator(); }
catch (SqlException e) {
try { tx.get().rollbackIfConnectionStillOpen(); }
catch (Exception ignored) { }
}
}
tx.set(fac.newDbTransaction());
return query().iterator();
}
}
public DbQueryResultSet query(final String sql, final Object... args) {
return new ReconnectingDbQueryResultSet() {
@Override protected DbQueryResultSet query() {
return tx.get().query(sql, args);
}
};
}
public DbQueryResultSet query(CharSequence sql, List> args) {
return query(sql.toString(), args.toArray());
}
}