Example usage for java.sql Connection TRANSACTION_READ_COMMITTED

List of usage examples for java.sql Connection TRANSACTION_READ_COMMITTED

Introduction

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

Prototype

int TRANSACTION_READ_COMMITTED

To view the source code for java.sql Connection TRANSACTION_READ_COMMITTED.

Click Source Link

Document

A constant indicating that dirty reads are prevented; non-repeatable reads and phantom reads can occur.

Usage

From source file:org.libx4j.dbcp.DataSources.java

public static BasicDataSource createDataSource(final $dbcp_dbcp dbcp) throws SQLException {
    if (dbcp.isNull())
        throw new BindingRuntimeException("/dbcp:jdbc is missing");

    final dbcp_dbcp._jdbc jdbc = dbcp._jdbc(0);
    final BasicDataSource dataSource = new BasicDataSource() {
        @Override/*from   w w  w. ja  va2  s.co m*/
        public Connection getConnection() throws SQLException {
            //        try {
            return super.getConnection();
            //        }
            //        catch (final SQLException e) {
            //          // TODO: Finish this!
            //          if ("Cannot get a connection, pool error Timeout waiting for idle object".equals(e.getMessage()))
            //            Throwables.set(e, "XX" + e.getMessage());
            //
            //          throw e;
            //        }
        }
    };

    if (jdbc._driverClassName(0).isNull())
        throw new BindingRuntimeException("/dbcp:jdbc/dbcp:driverClassName is missing");

    dataSource.setDriverClassName(jdbc._driverClassName(0).text());

    //    if (jdbc._loginTimeout() != null && jdbc._loginTimeout().size() != 0 && jdbc._loginTimeout(0).text() != null) {
    // FIXME: This causes a ClassNotFoundException: com.sybase.jdbc3.jdbc.SybDriver
    //      try {
    //        dataSource.setLoginTimeout(jdbc._loginTimeout(0).text());
    //      }
    //      catch(final SQLException e) {
    //        throw new SQLException(e);
    //      }
    //  }

    if (jdbc._url(0).isNull())
        throw new BindingRuntimeException("/dbcp:jdbc/dbcp:url is missing");

    dataSource.setUrl(jdbc._url(0).text());

    if (jdbc._username(0).isNull())
        throw new BindingRuntimeException("/dbcp:jdbc/dbcp:username is missing");

    dataSource.setUsername(jdbc._username(0).text());

    if (jdbc._password(0).isNull())
        throw new BindingRuntimeException("/dbcp:jdbc/dbcp:password is missing");

    dataSource.setPassword(jdbc._password(0).text());
    final dbcp_dbcp._default defaults = dbcp._default(0);
    if (!defaults._connectionProperties(0).isNull())
        for (final dbcp_dbcp._default._connectionProperties._property property : defaults
                ._connectionProperties(0)._property())
            if (property._name$() != null && property._name$().text() != null && property._value$() != null
                    && property._value$().text() != null)
                dataSource.addConnectionProperty(property._name$().text(), property._value$().text());

    if (!defaults._autoCommit(0).isNull())
        dataSource.setDefaultAutoCommit(defaults._autoCommit(0).text());

    if (!defaults._readOnly(0).isNull())
        dataSource.setDefaultReadOnly(defaults._readOnly(0).text());

    if (!defaults._transactionIsolation(0).isNull()) {
        if (dbcp_dbcp._default._transactionIsolation.NONE.text()
                .equals(defaults._transactionIsolation(0).text()))
            dataSource.setDefaultTransactionIsolation(Connection.TRANSACTION_NONE);
        else if (dbcp_dbcp._default._transactionIsolation.READ_5FCOMMITTED.text()
                .equals(defaults._transactionIsolation(0).text()))
            dataSource.setDefaultTransactionIsolation(Connection.TRANSACTION_READ_COMMITTED);
        else if (dbcp_dbcp._default._transactionIsolation.READ_5FUNCOMMITTED.text()
                .equals(defaults._transactionIsolation(0).text()))
            dataSource.setDefaultTransactionIsolation(Connection.TRANSACTION_READ_UNCOMMITTED);
        else if (dbcp_dbcp._default._transactionIsolation.REPEATABLE_5FREAD.text()
                .equals(defaults._transactionIsolation(0).text()))
            dataSource.setDefaultTransactionIsolation(Connection.TRANSACTION_REPEATABLE_READ);
        else if (dbcp_dbcp._default._transactionIsolation.SERIALIZABLE.text()
                .equals(defaults._transactionIsolation(0).text()))
            dataSource.setDefaultTransactionIsolation(Connection.TRANSACTION_SERIALIZABLE);
        else
            throw new UnsupportedOperationException(
                    "Unsupported transaction isolation: " + defaults._transactionIsolation(0).text());
    }

    final dbcp_dbcp._size size = dbcp._size(0);
    if (!size.isNull()) {
        if (!size._initialSize(0).isNull())
            dataSource.setInitialSize(size._initialSize(0).text().intValue());

        if (!size._maxActive(0).isNull())
            dataSource.setMaxTotal(size._maxActive(0).text().intValue());

        if (!size._maxIdle(0).isNull())
            dataSource.setMaxIdle(size._maxIdle(0).text().intValue());

        if (!size._minIdle(0).isNull())
            dataSource.setMinIdle(size._minIdle(0).text().intValue());

        if (!size._maxWait(0).isNull())
            dataSource.setMaxWaitMillis(size._maxWait(0).text().intValue());
    }

    final dbcp_dbcp._management management = dbcp._management(0);
    if (!management.isNull()) {
        if (!management._validationQuery(0).isNull())
            dataSource.setValidationQuery(management._validationQuery(0).text());

        if (!management._testOnBorrow(0).isNull())
            dataSource.setTestOnBorrow(management._testOnBorrow(0).text());

        if (!management._testOnReturn(0).isNull())
            dataSource.setTestOnReturn(management._testOnReturn(0).text());

        if (!management._testWhileIdle(0).isNull())
            dataSource.setTestWhileIdle(management._testWhileIdle(0).text());

        if (!management._timeBetweenEvictionRuns(0).isNull())
            dataSource
                    .setTimeBetweenEvictionRunsMillis(management._timeBetweenEvictionRuns(0).text().intValue());

        if (!management._numTestsPerEvictionRun(0).isNull())
            dataSource.setNumTestsPerEvictionRun(management._numTestsPerEvictionRun(0).text().intValue());

        if (!management._minEvictableIdleTime(0).isNull())
            dataSource.setMinEvictableIdleTimeMillis(management._minEvictableIdleTime(0).text().intValue());
    }

    final dbcp_dbcp._preparedStatements preparedStatements = dbcp._preparedStatements(0);
    if (!preparedStatements.isNull()) {
        if (!preparedStatements._poolPreparedStatements(0).isNull())
            dataSource.setPoolPreparedStatements(preparedStatements._poolPreparedStatements(0).text());

        if (!preparedStatements._maxOpenPreparedStatements(0).isNull())
            dataSource.setMaxOpenPreparedStatements(
                    preparedStatements._maxOpenPreparedStatements(0).text().intValue());
    }

    final dbcp_dbcp._removal removal = dbcp._removal(0);
    if (!removal.isNull()) {
        if (!removal._removeAbandoned(0).isNull())
            dataSource.setRemoveAbandonedOnBorrow(removal._removeAbandoned(0).text());

        if (!removal._removeAbandonedTimeout(0).isNull())
            dataSource.setRemoveAbandonedTimeout(removal._removeAbandonedTimeout(0).text().intValue());

        if (!removal._logAbandoned(0).isNull())
            dataSource.setLogAbandoned(removal._logAbandoned(0).text());
    }

    final dbcp_dbcp._logging logging = dbcp._logging(0);
    if (!logging.isNull()) {
        final Logger logger = LoggerFactory.getLogger(DataSources.class);
        final LoggerPrintWriter loggerPrintWriter = new LoggerPrintWriter(logger,
                Level.valueOf(logging._level(0).text()));
        dataSource.setLogWriter(loggerPrintWriter);
        dataSource.setLogExpiredConnections(
                !logging._logExpiredConnections(0).isNull() && logging._logExpiredConnections(0).text());
        if (!logging._logAbandoned(0).isNull() && logging._logAbandoned(0).text()) {
            dataSource.setAbandonedLogWriter(loggerPrintWriter);
            dataSource.setLogAbandoned(true);
        }
    }

    return dataSource;
}

From source file:com.amazon.carbonado.repo.jdbc.JDBCRepository.java

static int mapIsolationLevelToJdbc(IsolationLevel level) {
    switch (level) {
    case NONE://from  ww w  .jav a  2s .  c om
    default:
        return Connection.TRANSACTION_NONE;
    case READ_UNCOMMITTED:
        return Connection.TRANSACTION_READ_UNCOMMITTED;
    case READ_COMMITTED:
        return Connection.TRANSACTION_READ_COMMITTED;
    case REPEATABLE_READ:
        return Connection.TRANSACTION_REPEATABLE_READ;
    case SNAPSHOT:
        // TODO: not accurate for all databases.
        return Connection.TRANSACTION_SERIALIZABLE;
    case SERIALIZABLE:
        return Connection.TRANSACTION_SERIALIZABLE;
    }
}

From source file:com.openddal.test.BaseTestCase.java

private BasicDataSource newDataSource() {
    BasicDataSource ds = new BasicDataSource();
    ds.setDriverClassName(driverClassName);
    ds.setUrl(url);/*  w  w  w .  j a v a2  s. c  om*/
    ds.setDefaultTransactionIsolation(Connection.TRANSACTION_READ_COMMITTED);
    return ds;
}

From source file:com.scottieknows.test.autoconfigure.PostgresAutoConfiguration.java

@Lazy
@Bean//from   www  . j a  va2 s  .c  o m
@ConditionalOnMissingBean
public DataSource dataSource() {
    String url = format("jdbc:postgresql://%s:%s/%s?user=%s&password=%s", config.net().host(),
            config.net().port(), config.storage().dbName(), config.credentials().username(),
            config.credentials().password());
    DataSource rtn = new DataSource();
    rtn.setDriverClassName("org.postgresql.Driver");
    rtn.setUsername(props.getUsername());
    rtn.setPassword(props.getPassword());
    rtn.setUrl(url);
    rtn.setMinIdle(2);
    rtn.setMaxActive(4);
    rtn.setMaxIdle(4);
    rtn.setInitialSize(2);
    rtn.setMaxWait(30000);
    rtn.setJdbcInterceptors("StatementFinalizer;ResetAbandonedTimer");
    rtn.setValidationQuery("select 1");
    rtn.setTimeBetweenEvictionRunsMillis(30000);
    rtn.setMinEvictableIdleTimeMillis(60000);
    rtn.setValidationInterval(30000);
    rtn.setLogAbandoned(true);
    rtn.setRemoveAbandoned(true);
    rtn.setRemoveAbandonedTimeout(60);
    rtn.setJmxEnabled(true);
    rtn.setAbandonWhenPercentageFull(75);
    rtn.setTestOnBorrow(true);
    rtn.setDefaultTransactionIsolation(Connection.TRANSACTION_READ_COMMITTED);
    return rtn;
}

From source file:org.craftercms.cstudio.alfresco.activityfeed.CStudioActivityFeedDaoServiceImpl.java

@Override
public void initIndexes() {
    DataSource dataSource = sqlMapper.getDataSource();
    Connection connection = null;
    int oldval = -1;
    try {/*from www .  ja  v  a2  s.c  o  m*/
        connection = dataSource.getConnection();
        oldval = connection.getTransactionIsolation();
        if (oldval != Connection.TRANSACTION_READ_COMMITTED) {
            connection.setTransactionIsolation(Connection.TRANSACTION_READ_COMMITTED);
        }

        List<HashMap> checkTable = sqlMapper.queryForList(STATEMENT_CHECK_TABLE_EXISTS);
        if (checkTable == null || checkTable.size() < 1) {
            ScriptRunner scriptRunner = new ScriptRunner(connection, false, true);
            scriptRunner.runScript(Resources.getResourceAsReader(initializeScriptPath));
        }
        connection.commit();
        List<TableIndexCheckTO> indexCheckResult = sqlMapper.queryForList(STATEMENT_CHECK_USER_IDX);
        if (indexCheckResult == null || indexCheckResult.size() < 1) {
            sqlMapper.insert(STATEMENT_ADD_USER_IDX);
        }
        indexCheckResult = sqlMapper.queryForList(STATEMENT_CHECK_SITE_IDX);
        if (indexCheckResult == null || indexCheckResult.size() < 1) {
            sqlMapper.insert(STATEMENT_ADD_SITE_IDX);
        }
        indexCheckResult = sqlMapper.queryForList(STATEMENT_CHECK_CONTENT_IDX);
        if (indexCheckResult == null || indexCheckResult.size() < 1) {
            sqlMapper.insert(STATEMENT_ADD_CONTENT_IDX);
        }
        connection.commit();
        if (oldval != -1) {
            connection.setTransactionIsolation(oldval);
        }
    } catch (SQLException e) {
        LOGGER.error("Error while initializing CStudio Activity DB indexes.", e);
    } catch (IOException e) {
        LOGGER.error("Error while initializing CStudio Activity DB indexes.", e);
    } finally {
        if (connection != null) {
            try {
                connection.close();
            } catch (SQLException e) {
            }
            connection = null;
        }
    }
}

From source file:com.commander4j.sys.JHost.java

public synchronized boolean connect(String sessionID, String host, String sqlPath, String viewPath) {
    Connection tempConn;//from www. j a  v  a  2 s .  com
    boolean result = false;

    if (getSqlstatements().IsInitialised() == false) {

        getSqlstatements().setXMLFilename(sqlPath);
        getSqlstatements().setjdbcDriver(getDatabaseParameters().getjdbcDriver());
        getSqlstatements().loadSQLStatements(host);

        getViewstatements().setXMLFilename(viewPath);
        getViewstatements().setjdbcDriver(getDatabaseParameters().getjdbcDriver());
        getViewstatements().loadSQLStatements(host);

        getSqlstatements().setSubstitutions(getViewstatements().getSQLStatements());
        getSqlstatements().setInitialised();
    }

    if (connections.containsKey(sessionID) == false) {
        try {
            Class.forName(getDatabaseParameters().getjdbcDriver()).newInstance();
            try {
                logger.debug(getDatabaseParameters().getjdbcConnectString());
                DriverManager.setLoginTimeout(5);
                tempConn = DriverManager.getConnection(getDatabaseParameters().getjdbcConnectString(),
                        getDatabaseParameters().getjdbcUsername(), getDatabaseParameters().getjdbcPassword());
                tempConn.setAutoCommit(false);
                tempConn.setTransactionIsolation(Connection.TRANSACTION_READ_COMMITTED);
                ++instanceCount;
                addConnection(sessionID, tempConn);
                result = true;
                setConnected(sessionID, true);
                logger.debug("Opened connection for session ID : " + sessionID);
            } catch (Exception ex) {
                String err = "";
                try {
                    err = ex.getMessage().substring(0, ex.getMessage().indexOf("\n"));
                } catch (Exception ex2) {
                    err = ex.getMessage();
                }

                logger.fatal(ex);
                if (Common.sd.getData(sessionID, "silentExceptions").equals("Yes") == false) {
                    JUtility.errorBeep();
                    JSplashScreenUtils.hide();
                    JOptionPane.showMessageDialog(null, WordUtils.wrap(err, 100),
                            "Database Connection Error (" + getSiteDescription() + ")",
                            JOptionPane.ERROR_MESSAGE);
                }
                result = false;
            }
        } catch (Exception ex) {
            logger.fatal(ex);
            if (Common.sd.getData(sessionID, "silentExceptions").equals("Yes") == false) {
                JUtility.errorBeep();
                JOptionPane.showMessageDialog(null, "Invalid jdbc driver [" + ex.getMessage() + "]",
                        "Login Error (" + getSiteDescription() + ")", JOptionPane.ERROR_MESSAGE);
            }
            result = false;
        }
    }

    return result;
}

From source file:org.wso2.carbon.identity.core.persistence.JDBCPersistenceManager.java

/**
 * Returns an database connection for Identity data source.
 *
 * @return Database connection/*from w  ww. ja  v  a2s.c  o  m*/
 * @throws IdentityException Exception occurred when getting the data source.
 */
public Connection getDBConnection() throws IdentityRuntimeException {
    try {
        Connection dbConnection = dataSource.getConnection();
        dbConnection.setAutoCommit(false);
        dbConnection.setTransactionIsolation(Connection.TRANSACTION_READ_COMMITTED);
        return dbConnection;
    } catch (SQLException e) {
        String errMsg = "Error when getting a database connection object from the Identity data source.";
        throw new IdentityRuntimeException(errMsg, e);
    }
}

From source file:org.craftercms.cstudio.alfresco.objectstate.ObjectStateDAOServiceImpl.java

@Override
public void initIndexes() {
    DataSource dataSource = _sqlMapClient.getDataSource();
    Connection connection = null;
    int oldval = -1;
    try {/* w w  w.  j a v a  2 s .c o m*/
        connection = dataSource.getConnection();
        oldval = connection.getTransactionIsolation();
        if (oldval != Connection.TRANSACTION_READ_COMMITTED) {
            connection.setTransactionIsolation(Connection.TRANSACTION_READ_COMMITTED);
        }
        List<HashMap> checkTable = _sqlMapClient.queryForList(STATEMENT_CHECK_TABLE_EXISTS);
        if (checkTable == null || checkTable.size() < 1) {
            ScriptRunner scriptRunner = new ScriptRunner(connection, false, true);
            scriptRunner.runScript(Resources.getResourceAsReader(initializeScriptPath));
        } else {
            Integer checkColumnCTEUsername = (Integer) _sqlMapClient.queryForObject(STATEMENT_CHECK_PATH_SIZE);
            if (checkColumnCTEUsername < 2000) {
                ScriptRunner scriptRunner = new ScriptRunner(connection, false, true);
                scriptRunner.runScript(Resources.getResourceAsReader(
                        initializeScriptPath.replace("initialize.sql", "alter_path_column_size.sql")));
            }

        }
        List<HashMap> indexCheckResult = _sqlMapClient.queryForList(STATEMENT_CHECK_OBJECT_IDX);
        if (indexCheckResult == null || indexCheckResult.size() < 1) {
            _sqlMapClient.insert(STATEMENT_ADD_OBJECT_IDX);
        }
        connection.commit();
        if (oldval != -1) {
            connection.setTransactionIsolation(oldval);
        }
    } catch (SQLException e) {
        if (LOGGER.isErrorEnabled()) {
            LOGGER.error("Error while initializing Object State table DB indexes.", e);
        }
    } catch (IOException e) {
        if (LOGGER.isErrorEnabled()) {
            LOGGER.error("Error while initializing Sequence table DB indexes.", e);
        }
    } finally {
        if (connection != null) {
            try {
                connection.close();
            } catch (SQLException e) {
            }
            connection = null;
        }
    }
}

From source file:org.artifactory.storage.db.util.JdbcHelper.java

/**
 * return coneection isolation level back to read committed
 *
 * @param allowDirtyReads//from w ww.jav a 2  s  .c o m
 * @param con             sql connection
 * @throws SQLException
 */
private void updateConnectionIsolationLevelToReadCommitted(boolean allowDirtyReads, Connection con)
        throws SQLException {
    if (allowDirtyReads && con != null) {
        con.setTransactionIsolation(Connection.TRANSACTION_READ_COMMITTED);
    }
}

From source file:org.wso2.carbon.identity.user.store.count.jdbc.internal.InternalCountRetriever.java

private Connection getDBConnection() throws SQLException, UserStoreException {

    Connection dbConnection = IdentityDatabaseUtil.getUserDBConnection();
    if (dbConnection == null) {
        throw new UserStoreException("Could not create a database connection to User database");
    }//from   w  w w  . ja  v  a2s  . c o m
    dbConnection.setAutoCommit(false);
    dbConnection.setTransactionIsolation(Connection.TRANSACTION_READ_COMMITTED);
    return dbConnection;
}