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

com.databasesandlife.util.jdbc.ReadOnlyReconnectingDbConnection Maven / Gradle / Ivy

There is a newer version: 21.0.1
Show newest version
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()); } }




© 2015 - 2024 Weber Informatics LLC | Privacy Policy