Example usage for java.sql Connection getTransactionIsolation

List of usage examples for java.sql Connection getTransactionIsolation

Introduction

In this page you can find the example usage for java.sql Connection getTransactionIsolation.

Prototype

int getTransactionIsolation() throws SQLException;

Source Link

Document

Retrieves this Connection object's current transaction isolation level.

Usage

From source file:org.jumpmind.db.sql.JdbcSqlTemplate.java

public static void close(boolean autoCommitValue, int transactionIsolationLevel, Connection c) {
    try {//from   w  w  w.  j ava2  s. c  om
        if (c != null) {
            c.setAutoCommit(autoCommitValue);
            if (c.getTransactionIsolation() != transactionIsolationLevel) {
                c.setTransactionIsolation(transactionIsolationLevel);
            }
        }
    } catch (Throwable ex) {
    } finally {
        close(c);
    }
}

From source file:org.kawanfw.sql.servlet.ServerSqlDispatch.java

/**
 * Returns to client the Connection.getTransactionIsolation() value
 * /*from   ww w . j  av  a2 s  .co  m*/
 * @param out
 *            the servlet print writer
 */
private void getTransactionIsolation(HttpServletRequest request, CommonsConfigurator commonsConfigurator,
        SqlConfigurator sqlConfigurator, OutputStream out) throws SQLException, IOException {

    String connectionId = request.getParameter(ConnectionParms.CONNECTION_ID);

    int transactionIsolation = -1;

    if (connectionId.equals("0")) {
        // Server Stateless Mode
        Connection connection = null;

        try {
            connection = commonsConfigurator.getConnection();
            transactionIsolation = connection.getTransactionIsolation();
        } finally {
            // Release the connection
            ConnectionCloser.freeConnection(connection, sqlConfigurator);
        }
    } else {
        String username = request.getParameter(Parameter.USERNAME);

        ConnectionStore connectionStore = new ConnectionStore(username, connectionId);
        Connection connection = connectionStore.get();

        if (connection == null) {
            //out.println(TransferStatus.SEND_OK);
            //out.println(SqlReturnCode.SESSION_INVALIDATED);
            ServerSqlManager.writeLine(out, TransferStatus.SEND_OK);
            ServerSqlManager.writeLine(out, SqlReturnCode.SESSION_INVALIDATED);
            return;
        } else {
            transactionIsolation = connection.getTransactionIsolation();
        }
    }

    debug("transactionIsolation: " + transactionIsolation);

    //out.println(TransferStatus.SEND_OK);
    //out.println("" + transactionIsolation);
    ServerSqlManager.writeLine(out, TransferStatus.SEND_OK);
    ServerSqlManager.writeLine(out, "" + transactionIsolation);

}

From source file:org.openanzo.datasource.nodecentric.internal.NodeCentricDatasource.java

/**
 * Determine if the database is initialized, or is it already being initialized by another connection. First check if a specified table exists. If it does,
 * check the initialized status./*from  w ww  .  j  a  va 2s. c  o  m*/
 * 
 * @throws AnzoException
 *             {@link ExceptionConstants.RDB#FAILED_WAITING_DB_INIT} if there was a problem waiting for the initialization status
 * @throws AnzoException
 *             {@link ExceptionConstants.RDB#FAILED_GET_INIT_STATUS} if there was a problem querying for the initialization status
 * @throws AnzoException
 *             {@link ExceptionConstants.RDB#FAILED_SETTING_ISOLATION} if there was a problem changing the transaction isolation level
 */
private boolean isInitialized(Connection connection, String tablename) throws AnzoException {
    int isolation = Connection.TRANSACTION_REPEATABLE_READ;
    if (configuration.getSupportsIsolation()) {
        try {
            isolation = connection.getTransactionIsolation();
            connection.setTransactionIsolation(Connection.TRANSACTION_REPEATABLE_READ);
        } catch (SQLException e) {
            log.error(LogUtils.RDB_MARKER, "Error setting tranaction isolation", e);
            throw new AnzoException(ExceptionConstants.RDB.FAILED_SETTING_ISOLATION, e);
        }
    }
    try {
        ResultSet rs = null;
        //Need to check all the tables, and not just the server table.  If we only check the server table, we could overwrite tables containing data.
        try {
            try {
                rs = connection.getMetaData().getTables(null, null,
                        configuration.getUsesUppercase() ? serverUpper : serverLower, new String[] { table });
                if (!rs.next()) {
                    return !checkIfTablesExists(connection, true);
                }
                String tbl = rs.getString(3);
                if (!tbl.equalsIgnoreCase(serverUpper)) {
                    return !checkIfTablesExists(connection, true);
                }
            } finally {
                if (rs != null) {
                    rs.close();
                }
            }
        } catch (SQLException e) {
            log.error(LogUtils.RDB_MARKER, "error checking tables", e);
            throw new AnzoException(ExceptionConstants.RDB.FAILED_GETTING_TABLE_STATUS, e, serverUpper);
        }
        try {
            long initialized = 2;
            int retries = 0;
            //While the server is initializing in another connection, wait. Wait a total of 20 seconds, and then fail.
            while (initialized > 1) {
                if (retries++ < 30) {
                    Long init = ServerRdbWrapper.getInitialized(statementProvider, connection);
                    if (init == null) {
                        return true;
                    }
                    initialized = init.longValue();
                    if (initialized > 1) {
                        if ((System.currentTimeMillis() - initialized) > 60000) {
                            log.error(LogUtils.RDB_MARKER,
                                    "A previous connections was intializing the database, but its been over a minute, so assume a fauilure");
                            ServerRdbWrapper.setInitializingFailed(statementProvider, connection);
                            return false;
                        }
                        try {
                            Thread.sleep(1000);
                        } catch (InterruptedException ie) {
                        }
                    }
                } else {
                    throw new AnzoException(ExceptionConstants.RDB.FAILED_WAITING_DB_INIT);
                }
            }
            checkIfTablesExists(connection, false);
            return true;
        } catch (RdbException e) {
            log.error(LogUtils.RDB_MARKER, "Error checking initialization state", e);
            throw new AnzoException(ExceptionConstants.RDB.FAILED_GET_INIT_STATUS, e);
        }
    } finally {
        try {
            if (configuration.getSupportsIsolation()) {
                connection.setTransactionIsolation(isolation);
            }
        } catch (SQLException e) {
            log.error(LogUtils.RDB_MARKER, "Error setting transaction isolation level", e);
            throw new AnzoException(ExceptionConstants.RDB.FAILED_SETTING_ISOLATION, e);
        }
    }
}

From source file:org.openconcerto.sql.model.SQLDataSource.java

final synchronized void setTransactionIsolation(Connection conn) throws SQLException {
    if (this.dbTxIsolation == null) {
        this.dbTxIsolation = conn.getTransactionIsolation();
        assert this.dbTxIsolation != null;
    }// w ww . j av  a2  s. co m
    // no need to try to change the level if the DB doesn't support transactions
    if (this.dbTxIsolation != Connection.TRANSACTION_NONE
            && (!this.checkOnceDBTxIsolation || this.dbTxIsolation != this.txIsolation)) {
        // if not check once, it's the desired action, so don't log
        if (this.checkOnceDBTxIsolation)
            Log.get().config("Setting transaction isolation to " + this.txIsolation);
        conn.setTransactionIsolation(this.txIsolation);
    }
}

From source file:org.opendatakit.common.persistence.engine.pgres.TaskLockImpl.java

private TaskLockTable doTransaction(TaskLockTable entity, long l)
        throws ODKEntityNotFoundException, ODKTaskLockException {
    boolean first;

    final List<String> stmts = new ArrayList<String>();

    String uri = entity.getUri();

    StringBuilder b = new StringBuilder();
    String tableName = K_BQ + datastore.getDefaultSchemaName() + K_BQ + "." + K_BQ + TaskLockTable.TABLE_NAME
            + K_BQ;//  ww w . ja va2  s.  c om

    b.append("'").append(user.getUriUser().replaceAll("'", "''")).append("'");
    String uriUserInline = b.toString();
    b.setLength(0);
    b.append("'").append(uri.replaceAll("'", "''")).append("'");
    String uriLockInline = b.toString();
    b.setLength(0);
    b.append("'").append(entity.getFormId().replaceAll("'", "''")).append("'");
    String formIdInline = b.toString();
    b.setLength(0);
    b.append("'").append(entity.getTaskType().replaceAll("'", "''")).append("'");
    String taskTypeInline = b.toString();
    b.setLength(0);
    b.append("interval '").append(l).append(" milliseconds'");
    String lifetimeIntervalMilliseconds = b.toString();
    b.setLength(0);

    b.append("LOCK TABLE ").append(tableName).append(" IN ACCESS EXCLUSIVE MODE");
    stmts.add(b.toString());
    b.setLength(0);

    dam.recordPutUsage(TaskLockTable.TABLE_NAME);
    if (!entity.isFromDatabase()) {
        // insert a new record (prospective lock)
        b.append("INSERT INTO ");
        b.append(tableName);
        b.append(" (");
        first = true;
        for (DataField f : entity.getFieldList()) {
            if (!first) {
                b.append(",");
            }
            first = false;
            b.append(K_BQ);
            b.append(f.getName());
            b.append(K_BQ);
        }
        first = true;
        b.append(") VALUES ( ");
        for (DataField f : entity.getFieldList()) {
            if (!first) {
                b.append(",");
            }
            first = false;
            if (f.equals(entity.creationDate) || f.equals(entity.lastUpdateDate)) {
                b.append("NOW()");
            } else if (f.equals(entity.creatorUriUser) || f.equals(entity.lastUpdateUriUser)) {
                b.append(uriUserInline);
            } else if (f.equals(entity.formId)) {
                b.append(formIdInline);
            } else if (f.equals(entity.taskType)) {
                b.append(taskTypeInline);
            } else if (f.equals(entity.primaryKey)) {
                b.append(uriLockInline);
            } else if (f.equals(entity.expirationDateTime)) {
                b.append(" NOW() + ");
                b.append(lifetimeIntervalMilliseconds);
            } else {
                throw new IllegalStateException("unexpected case " + f.getName());
            }
        }
        b.append(")");
        stmts.add(b.toString());
        b.setLength(0);
    } else {
        // update existing record (prospective lock)
        b.append("UPDATE ");
        b.append(tableName);
        b.append(" SET ");
        first = true;
        for (DataField f : entity.getFieldList()) {
            if (f == entity.primaryKey)
                continue;
            if (!first) {
                b.append(",");
            }
            first = false;
            b.append(K_BQ);
            b.append(f.getName());
            b.append(K_BQ);
            b.append(" = ");
            if (f.equals(entity.creationDate) || f.equals(entity.lastUpdateDate)) {
                b.append("NOW()");
            } else if (f.equals(entity.creatorUriUser) || f.equals(entity.lastUpdateUriUser)) {
                b.append(uriUserInline);
            } else if (f.equals(entity.formId)) {
                b.append(formIdInline);
            } else if (f.equals(entity.taskType)) {
                b.append(taskTypeInline);
            } else if (f.equals(entity.primaryKey)) {
                b.append(uriLockInline);
            } else if (f.equals(entity.expirationDateTime)) {
                b.append(" NOW() + ");
                b.append(lifetimeIntervalMilliseconds);
            } else {
                throw new IllegalStateException("unexpected case " + f.getName());
            }
        }
        b.append(" WHERE ");
        b.append(K_BQ);
        b.append(entity.primaryKey.getName());
        b.append(K_BQ);
        b.append(" = ");
        b.append(uriLockInline);
        stmts.add(b.toString());
        b.setLength(0);
    }
    // delete stale locks (don't care who's)
    dam.recordDeleteUsage(TaskLockTable.TABLE_NAME);
    b.append("DELETE FROM ").append(tableName).append(" WHERE ");
    b.append(K_BQ).append(entity.expirationDateTime.getName()).append(K_BQ).append(" <= NOW()");
    stmts.add(b.toString());
    b.setLength(0);
    // delete prospective locks which are not the oldest for that resource and
    // task type
    dam.recordDeleteUsage(TaskLockTable.TABLE_NAME);
    b.append("DELETE FROM ").append(tableName).append(" WHERE ");
    b.append(K_BQ).append(entity.formId.getName()).append(K_BQ).append(" = ").append(formIdInline)
            .append(" AND ");
    b.append(K_BQ).append(entity.taskType.getName()).append(K_BQ).append(" = ").append(taskTypeInline)
            .append(" AND ");
    b.append(K_BQ).append(entity.expirationDateTime.getName()).append(K_BQ);
    b.append(" > (SELECT MIN(t3.").append(K_BQ).append(entity.expirationDateTime.getName()).append(K_BQ);
    b.append(") FROM ").append(tableName).append(" AS t3 WHERE t3.");
    b.append(K_BQ).append(entity.formId.getName()).append(K_BQ).append(" = ").append(formIdInline)
            .append(" AND t3.");
    b.append(K_BQ).append(entity.taskType.getName()).append(K_BQ).append(" = ").append(taskTypeInline)
            .append(")");
    stmts.add(b.toString());
    b.setLength(0);
    // delete our entry if it collides with another entry with exactly 
    // this time.
    b.append("DELETE FROM ").append(tableName).append(" WHERE ");
    b.append(K_BQ).append(entity.formId.getName()).append(K_BQ).append(" = ").append(formIdInline)
            .append(" AND ");
    b.append(K_BQ).append(entity.taskType.getName()).append(K_BQ).append(" = ").append(taskTypeInline)
            .append(" AND ");
    b.append(K_BQ).append(entity.primaryKey.getName()).append(K_BQ).append(" = ").append(uriLockInline)
            .append(" AND ");
    b.append("1 < (SELECT COUNT(t3.").append(K_BQ).append(entity.expirationDateTime.getName()).append(K_BQ);
    b.append(") FROM ").append(tableName).append(" AS t3 WHERE t3.");
    b.append(K_BQ).append(entity.formId.getName()).append(K_BQ).append(" = ").append(formIdInline)
            .append(" AND t3.");
    b.append(K_BQ).append(entity.taskType.getName()).append(K_BQ).append(" = ").append(taskTypeInline)
            .append(")");
    stmts.add(b.toString());
    b.setLength(0);
    // assert: only the lock that holds the resource for that task type appears
    // in the task lock table
    TaskLockTable relation;
    try {

        JdbcTemplate jdbc = datastore.getJdbcConnection();
        jdbc.execute(new ConnectionCallback<Object>() {

            @Override
            public Object doInConnection(Connection conn) throws SQLException, DataAccessException {
                boolean oldAutoCommitValue = conn.getAutoCommit();
                int oldTransactionValue = conn.getTransactionIsolation();
                try {
                    conn.setAutoCommit(false);
                    conn.setTransactionIsolation(Connection.TRANSACTION_SERIALIZABLE);
                    Statement stmt = conn.createStatement();
                    for (String s : stmts) {
                        // for debugging: LogFactory.getLog(TaskLockImpl.class).info(s);
                        stmt.execute(s);
                    }
                    conn.commit();
                } catch (Exception e) {
                    e.printStackTrace();
                    conn.rollback();
                }
                conn.setTransactionIsolation(oldTransactionValue);
                conn.setAutoCommit(oldAutoCommitValue);
                return null;
            }

        });

        relation = TaskLockTable.assertRelation(datastore, user);
    } catch (Exception e) {
        throw new ODKTaskLockException(PERSISTENCE_LAYER_PROBLEM, e);
    }
    return (TaskLockTable) datastore.getEntity(relation, entity.getUri(), user);
}

From source file:org.opendatakit.common.persistence.engine.sqlserver.TaskLockImpl.java

private TaskLockTable doTransaction(TaskLockTable entity, long l)
        throws ODKEntityNotFoundException, ODKTaskLockException {
    boolean first;

    final List<String> stmts = new ArrayList<String>();

    String uri = entity.getUri();

    StringBuilder b = new StringBuilder();
    String tableName = K_BQ + datastore.getDefaultSchemaName() + K_BQ + "." + K_BQ + TaskLockTable.TABLE_NAME
            + K_BQ;//from   w  w  w  .ja va2  s  . c  o  m

    b.append("'").append(user.getUriUser().replaceAll("'", "''")).append("'");
    String uriUserInline = b.toString();
    b.setLength(0);
    b.append("'").append(uri.replaceAll("'", "''")).append("'");
    String uriLockInline = b.toString();
    b.setLength(0);
    b.append("'").append(entity.getFormId().replaceAll("'", "''")).append("'");
    String formIdInline = b.toString();
    b.setLength(0);
    b.append("'").append(entity.getTaskType().replaceAll("'", "''")).append("'");
    String taskTypeInline = b.toString();
    b.setLength(0);
    b.append("DATEADD(ms,").append(l).append(",SYSUTCDATETIME())");
    String nowPlusLifetimeIntervalMilliseconds = b.toString();
    b.setLength(0);

    b.append("SELECT  COUNT(1) FROM ").append(tableName).append(" WITH (TABLOCKX, HOLDLOCK)");
    stmts.add(b.toString());
    b.setLength(0);

    dam.recordPutUsage(TaskLockTable.TABLE_NAME);
    if (!entity.isFromDatabase()) {
        // insert a new record (prospective lock)
        b.append("INSERT INTO ");
        b.append(tableName);
        b.append(" (");
        first = true;
        for (DataField f : entity.getFieldList()) {
            if (!first) {
                b.append(",");
            }
            first = false;
            b.append(K_BQ);
            b.append(f.getName());
            b.append(K_BQ);
        }
        first = true;
        b.append(") VALUES ( ");
        for (DataField f : entity.getFieldList()) {
            if (!first) {
                b.append(",");
            }
            first = false;
            if (f.equals(entity.creationDate) || f.equals(entity.lastUpdateDate)) {
                b.append("SYSUTCDATETIME()");
            } else if (f.equals(entity.creatorUriUser) || f.equals(entity.lastUpdateUriUser)) {
                b.append(uriUserInline);
            } else if (f.equals(entity.formId)) {
                b.append(formIdInline);
            } else if (f.equals(entity.taskType)) {
                b.append(taskTypeInline);
            } else if (f.equals(entity.primaryKey)) {
                b.append(uriLockInline);
            } else if (f.equals(entity.expirationDateTime)) {
                b.append(nowPlusLifetimeIntervalMilliseconds);
            } else {
                throw new IllegalStateException("unexpected case " + f.getName());
            }
        }
        b.append(")");
        stmts.add(b.toString());
        b.setLength(0);
    } else {
        // update existing record (prospective lock)
        b.append("UPDATE ");
        b.append(tableName);
        b.append(" SET ");
        first = true;
        for (DataField f : entity.getFieldList()) {
            if (f == entity.primaryKey)
                continue;
            if (!first) {
                b.append(",");
            }
            first = false;
            b.append(K_BQ);
            b.append(f.getName());
            b.append(K_BQ);
            b.append(" = ");
            if (f.equals(entity.creationDate) || f.equals(entity.lastUpdateDate)) {
                b.append("SYSUTCDATETIME()");
            } else if (f.equals(entity.creatorUriUser) || f.equals(entity.lastUpdateUriUser)) {
                b.append(uriUserInline);
            } else if (f.equals(entity.formId)) {
                b.append(formIdInline);
            } else if (f.equals(entity.taskType)) {
                b.append(taskTypeInline);
            } else if (f.equals(entity.primaryKey)) {
                b.append(uriLockInline);
            } else if (f.equals(entity.expirationDateTime)) {
                b.append(nowPlusLifetimeIntervalMilliseconds);
            } else {
                throw new IllegalStateException("unexpected case " + f.getName());
            }
        }
        b.append(" WHERE ");
        b.append(K_BQ);
        b.append(entity.primaryKey.getName());
        b.append(K_BQ);
        b.append(" = ");
        b.append(uriLockInline);
        stmts.add(b.toString());
        b.setLength(0);
    }
    // delete stale locks (don't care who's)
    dam.recordDeleteUsage(TaskLockTable.TABLE_NAME);
    b.append("DELETE FROM ").append(tableName).append(" WHERE ");
    b.append(K_BQ).append(entity.expirationDateTime.getName()).append(K_BQ).append(" <= SYSUTCDATETIME()");
    stmts.add(b.toString());
    b.setLength(0);
    // delete prospective locks which are not the oldest for that resource and
    // task type
    dam.recordDeleteUsage(TaskLockTable.TABLE_NAME);
    b.append("DELETE FROM ").append(tableName).append(" WHERE ");
    b.append(K_BQ).append(entity.formId.getName()).append(K_BQ).append(" = ").append(formIdInline)
            .append(" AND ");
    b.append(K_BQ).append(entity.taskType.getName()).append(K_BQ).append(" = ").append(taskTypeInline)
            .append(" AND ");
    b.append(K_BQ).append(entity.expirationDateTime.getName()).append(K_BQ);
    b.append(" > (SELECT MIN(t3.").append(K_BQ).append(entity.expirationDateTime.getName()).append(K_BQ);
    b.append(") FROM ").append(tableName).append(" AS t3 WHERE t3.");
    b.append(K_BQ).append(entity.formId.getName()).append(K_BQ).append(" = ").append(formIdInline)
            .append(" AND t3.");
    b.append(K_BQ).append(entity.taskType.getName()).append(K_BQ).append(" = ").append(taskTypeInline)
            .append(")");
    stmts.add(b.toString());
    b.setLength(0);
    // delete our entry if it collides with another entry with exactly 
    // this time.
    b.append("DELETE FROM ").append(tableName).append(" WHERE ");
    b.append(K_BQ).append(entity.formId.getName()).append(K_BQ).append(" = ").append(formIdInline)
            .append(" AND ");
    b.append(K_BQ).append(entity.taskType.getName()).append(K_BQ).append(" = ").append(taskTypeInline)
            .append(" AND ");
    b.append(K_BQ).append(entity.primaryKey.getName()).append(K_BQ).append(" = ").append(uriLockInline)
            .append(" AND ");
    b.append("1 < (SELECT COUNT(t3.").append(K_BQ).append(entity.expirationDateTime.getName()).append(K_BQ);
    b.append(") FROM ").append(tableName).append(" AS t3 WHERE t3.");
    b.append(K_BQ).append(entity.formId.getName()).append(K_BQ).append(" = ").append(formIdInline)
            .append(" AND t3.");
    b.append(K_BQ).append(entity.taskType.getName()).append(K_BQ).append(" = ").append(taskTypeInline)
            .append(")");
    stmts.add(b.toString());
    b.setLength(0);
    // assert: only the lock that holds the resource for that task type appears
    // in the task lock table
    TaskLockTable relation;
    try {

        JdbcTemplate jdbc = datastore.getJdbcConnection();
        jdbc.execute(new ConnectionCallback<Object>() {

            @Override
            public Object doInConnection(Connection conn) throws SQLException, DataAccessException {
                boolean oldAutoCommitValue = conn.getAutoCommit();
                int oldTransactionValue = conn.getTransactionIsolation();
                try {
                    conn.setAutoCommit(false);
                    conn.setTransactionIsolation(Connection.TRANSACTION_SERIALIZABLE);
                    Statement stmt = conn.createStatement();
                    for (String s : stmts) {
                        // for debugging: LogFactory.getLog(TaskLockImpl.class).info(s);
                        stmt.execute(s);
                    }
                    conn.commit();
                } catch (Exception e) {
                    e.printStackTrace();
                    conn.rollback();
                }
                conn.setTransactionIsolation(oldTransactionValue);
                conn.setAutoCommit(oldAutoCommitValue);
                return null;
            }

        });

        relation = TaskLockTable.assertRelation(datastore, user);
    } catch (Exception e) {
        throw new ODKTaskLockException(PERSISTENCE_LAYER_PROBLEM, e);
    }
    return (TaskLockTable) datastore.getEntity(relation, entity.getUri(), user);
}

From source file:org.rimudb.C3P0PoolTests.java

@Test
public void testConnectionAttributes() throws Exception {
    // Connect to the database
    CompoundDatabase cdb = new CompoundDatabase("/testconfig/pooltests-c3p0-2-jdbcconfig.xml", true);

    cdb.connect("dbid-1");
    Database db = cdb.getDatabase("dbid-1");
    Connection conn = db.getDatabaseConnection();
    assertEquals("Wrong transaction isolation", Connection.TRANSACTION_READ_COMMITTED,
            conn.getTransactionIsolation());
    assertEquals("Wrong auto commit", false, conn.getAutoCommit());
    db.disconnect();/*from  ww w  . ja  v  a2 s  .c o m*/

    cdb.connect("dbid-2");
    db = cdb.getDatabase("dbid-2");
    conn = db.getDatabaseConnection();
    assertEquals("Wrong transaction isolation", Connection.TRANSACTION_READ_UNCOMMITTED,
            conn.getTransactionIsolation());
    assertEquals("Wrong auto commit", true, conn.getAutoCommit());
    db.disconnect();

    cdb.connect("dbid-3");
    db = cdb.getDatabase("dbid-3");
    conn = db.getDatabaseConnection();
    assertEquals("Wrong transaction isolation", Connection.TRANSACTION_REPEATABLE_READ,
            conn.getTransactionIsolation());
    assertEquals("Wrong auto commit", false, conn.getAutoCommit());
    db.disconnect();

    cdb.connect("dbid-4");
    db = cdb.getDatabase("dbid-4");
    conn = db.getDatabaseConnection();
    assertEquals("Wrong transaction isolation", Connection.TRANSACTION_SERIALIZABLE,
            conn.getTransactionIsolation());
    assertEquals("Wrong auto commit", true, conn.getAutoCommit());
    db.disconnect();

    cdb.disconnectAllNoException();
}

From source file:org.rimudb.DBCPPoolTests.java

@Test
public void testConnectionAttributes() throws Exception {
    // Connect to the database
    CompoundDatabase cdb = new CompoundDatabase("/testconfig/pooltests-dbcp-2-jdbcconfig.xml", true);

    cdb.connect("dbid-1");
    Database db = cdb.getDatabase("dbid-1");
    Connection conn = db.getDatabaseConnection();
    assertEquals("Wrong transaction isolation", Connection.TRANSACTION_READ_COMMITTED,
            conn.getTransactionIsolation());
    assertEquals("Wrong auto commit", false, conn.getAutoCommit());
    db.disconnect();//from w  w  w . j  av a  2  s. co m

    cdb.connect("dbid-2");
    db = cdb.getDatabase("dbid-2");
    conn = db.getDatabaseConnection();
    assertEquals("Wrong transaction isolation", Connection.TRANSACTION_READ_UNCOMMITTED,
            conn.getTransactionIsolation());
    assertEquals("Wrong auto commit", true, conn.getAutoCommit());
    db.disconnect();

    cdb.connect("dbid-3");
    db = cdb.getDatabase("dbid-3");
    conn = db.getDatabaseConnection();
    assertEquals("Wrong transaction isolation", Connection.TRANSACTION_REPEATABLE_READ,
            conn.getTransactionIsolation());
    assertEquals("Wrong auto commit", false, conn.getAutoCommit());
    db.disconnect();

    cdb.connect("dbid-4");
    db = cdb.getDatabase("dbid-4");
    conn = db.getDatabaseConnection();
    assertEquals("Wrong transaction isolation", Connection.TRANSACTION_SERIALIZABLE,
            conn.getTransactionIsolation());
    assertEquals("Wrong auto commit", true, conn.getAutoCommit());
    db.disconnect();

    cdb.disconnectAllNoException();
}

From source file:org.springframework.jdbc.datasource.DataSourceUtils.java

/**
 * Prepare the given Connection with the given transaction semantics.
 * @param con the Connection to prepare/* w w  w .j av  a  2  s  .com*/
 * @param definition the transaction definition to apply
 * @return the previous isolation level, if any
 * @throws SQLException if thrown by JDBC methods
 * @see #resetConnectionAfterTransaction
 */
@Nullable
public static Integer prepareConnectionForTransaction(Connection con,
        @Nullable TransactionDefinition definition) throws SQLException {

    Assert.notNull(con, "No Connection specified");

    // Set read-only flag.
    if (definition != null && definition.isReadOnly()) {
        try {
            if (logger.isDebugEnabled()) {
                logger.debug("Setting JDBC Connection [" + con + "] read-only");
            }
            con.setReadOnly(true);
        } catch (SQLException | RuntimeException ex) {
            Throwable exToCheck = ex;
            while (exToCheck != null) {
                if (exToCheck.getClass().getSimpleName().contains("Timeout")) {
                    // Assume it's a connection timeout that would otherwise get lost: e.g. from JDBC 4.0
                    throw ex;
                }
                exToCheck = exToCheck.getCause();
            }
            // "read-only not supported" SQLException -> ignore, it's just a hint anyway
            logger.debug("Could not set JDBC Connection read-only", ex);
        }
    }

    // Apply specific isolation level, if any.
    Integer previousIsolationLevel = null;
    if (definition != null && definition.getIsolationLevel() != TransactionDefinition.ISOLATION_DEFAULT) {
        if (logger.isDebugEnabled()) {
            logger.debug("Changing isolation level of JDBC Connection [" + con + "] to "
                    + definition.getIsolationLevel());
        }
        int currentIsolation = con.getTransactionIsolation();
        if (currentIsolation != definition.getIsolationLevel()) {
            previousIsolationLevel = currentIsolation;
            con.setTransactionIsolation(definition.getIsolationLevel());
        }
    }

    return previousIsolationLevel;
}

From source file:org.springframework.jdbc.datasource.LazyConnectionDataSourceProxy.java

/**
 * Check the default connection properties (auto-commit, transaction isolation),
 * keeping them to be able to expose them correctly without fetching an actual
 * JDBC Connection from the target DataSource.
 * <p>This will be invoked once on startup, but also for each retrieval of a
 * target Connection. If the check failed on startup (because the database was
 * down), we'll lazily retrieve those settings.
 * @param con the Connection to use for checking
 * @throws SQLException if thrown by Connection methods
 *///from  www  . ja v  a 2 s  .co m
protected synchronized void checkDefaultConnectionProperties(Connection con) throws SQLException {
    if (this.defaultAutoCommit == null) {
        this.defaultAutoCommit = con.getAutoCommit();
    }
    if (this.defaultTransactionIsolation == null) {
        this.defaultTransactionIsolation = con.getTransactionIsolation();
    }
}