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.wso2.carbon.identity.account.suspension.notification.task.jdbc.JDBCNotificationReceiversRetrieval.java

private Connection getDBConnection(RealmConfiguration realmConfiguration)
        throws SQLException, UserStoreException {

    Connection dbConnection = null;
    DataSource dataSource = DatabaseUtil.createUserStoreDataSource(realmConfiguration);

    if (dataSource != null) {
        dbConnection = DatabaseUtil.getDBConnection(dataSource);
    }/*w  w w  .  j  av  a 2 s . c o  m*/

    //if primary user store, DB connection can be same as realm data source.
    if (dbConnection == null && realmConfiguration.isPrimary()) {
        dbConnection = IdentityDatabaseUtil.getUserDBConnection();
    } else if (dbConnection == null) {
        throw new UserStoreException("Could not create a database connection to "
                + realmConfiguration.getUserStoreProperty(UserCoreConstants.RealmConfig.PROPERTY_DOMAIN_NAME));
    } else {
        // db connection is present
    }
    dbConnection.setAutoCommit(false);
    dbConnection.setTransactionIsolation(Connection.TRANSACTION_READ_COMMITTED);
    return dbConnection;
}

From source file:org.apache.sqoop.mapreduce.db.SQLServerDBRecordReader.java

/**
 * Configure the provided Connection for record reads.
 */// ww  w. ja  v a  2  s .  co m
protected void configureConnection(Connection conn) throws IOException {
    try {
        conn.setAutoCommit(false);
        conn.setTransactionIsolation(Connection.TRANSACTION_READ_COMMITTED);
    } catch (SQLException sqlEx) {
        LOG.error("Failed to configure SQL Connection");
        throw new IOException(sqlEx);
    }
}

From source file:org.wso2.carbon.repository.core.jdbc.dao.JDBCLogsDAO.java

private void addLogRecords(LogRecord[] logRecords, JDBCDataAccessManager dataAccessManager)
        throws RepositoryException {
    PreparedStatement s = null;//from   w  w w. j a v  a 2 s .co  m
    Connection conn = null;

    try {
        conn = dataAccessManager.getDataSource().getConnection();
        if (conn.getTransactionIsolation() != Connection.TRANSACTION_READ_COMMITTED) {
            conn.setTransactionIsolation(Connection.TRANSACTION_READ_COMMITTED);
        }
        conn.setAutoCommit(false);
        String sql = "INSERT INTO REG_LOG (REG_PATH, REG_USER_ID, REG_LOGGED_TIME, "
                + "REG_ACTION, REG_ACTION_DATA, REG_TENANT_ID) " + "VALUES (?, ?, ?, ?, ?, ?)";

        s = conn.prepareStatement(sql);
        for (LogRecord logRecord : logRecords) {
            s.clearParameters();
            s.setString(1, logRecord.getResourcePath());
            s.setString(2, logRecord.getUserName());
            s.setTimestamp(3, new Timestamp(logRecord.getTimestamp().getTime()));
            s.setInt(4, logRecord.getAction().getId());
            s.setString(5, logRecord.getActionData());
            s.setInt(6, logRecord.getTenantId());
            s.addBatch();
        }
        int[] status = s.executeBatch();
        if (log.isDebugEnabled()) {
            log.debug("Successfully added " + status.length + " log records.");
        }
        conn.commit();

    } catch (SQLException e) {
        try {
            if (conn != null) {
                conn.rollback();
            }
        } catch (SQLException e1) {
            log.error("Failed to rollback log insertion.", e);
        }
        String msg = "Failed to update log batch records " + ". " + e.getMessage();
        log.error(msg, e);
        throw new RepositoryDBException(msg, e);
    } finally {
        try {
            if (s != null) {
                s.close();
            }
            if (conn != null && !(conn.isClosed())) {
                conn.close();
            }
        } catch (SQLException ex) {
            String msg = InternalConstants.RESULT_SET_PREPARED_STATEMENT_CLOSE_ERROR;
            log.error(msg, ex);
        }
    }
}

From source file:org.wso2.carbon.registry.core.jdbc.dao.JDBCLogsDAO.java

private void addLogRecords(LogRecord[] logRecords, JDBCDataAccessManager dataAccessManager)
        throws RegistryException {
    PreparedStatement s = null;//from   w  ww  . jav a2  s.c o  m
    Connection conn = null;
    try {
        conn = dataAccessManager.getDataSource().getConnection();
        if (conn.getTransactionIsolation() != Connection.TRANSACTION_READ_COMMITTED) {
            conn.setTransactionIsolation(Connection.TRANSACTION_READ_COMMITTED);
        }
        conn.setAutoCommit(false);
        String sql = "INSERT INTO REG_LOG (REG_PATH, REG_USER_ID, REG_LOGGED_TIME, "
                + "REG_ACTION, REG_ACTION_DATA, REG_TENANT_ID) " + "VALUES (?, ?, ?, ?, ?, ?)";

        s = conn.prepareStatement(sql);
        for (LogRecord logRecord : logRecords) {
            s.clearParameters();
            s.setString(1, logRecord.getResourcePath());
            s.setString(2, logRecord.getUserName());
            s.setTimestamp(3, new Timestamp(logRecord.getTimestamp().getTime()));
            s.setInt(4, logRecord.getAction());
            s.setString(5, logRecord.getActionData());
            s.setInt(6, logRecord.getTenantId());
            s.addBatch();
        }
        int[] status = s.executeBatch();
        if (log.isDebugEnabled()) {
            log.debug("Successfully added " + status.length + " log records.");
        }
        conn.commit();

    } catch (SQLException e) {
        try {
            if (conn != null) {
                conn.rollback();
            }
        } catch (SQLException e1) {
            log.error("Failed to rollback log insertion.", e);
        }
        String msg = "Failed to update log batch records " + ". " + e.getMessage();
        log.error(msg, e);
        throw new RegistryException(msg, e);
    } finally {
        try {
            if (s != null) {
                s.close();
            }
            if (conn != null && !(conn.isClosed())) {
                conn.close();
            }
        } catch (SQLException ex) {
            String msg = RegistryConstants.RESULT_SET_PREPARED_STATEMENT_CLOSE_ERROR;
            log.error(msg, ex);
        }
    }
}

From source file:com.zaxxer.hikari.benchmark.BenchBase.java

private void setupDBCP2() {
    org.apache.commons.pool2.impl.GenericObjectPool<org.apache.commons.dbcp2.PoolableConnection> connectionPool;
    DriverManagerConnectionFactory connectionFactory = new DriverManagerConnectionFactory(jdbcURL, "sa", "");

    // Wrap the connections and statements with pooled variants
    org.apache.commons.dbcp2.PoolableConnectionFactory poolableCF = null;
    poolableCF = new org.apache.commons.dbcp2.PoolableConnectionFactory(connectionFactory, null);

    poolableCF.setValidationQuery("VALUES 1");
    poolableCF.setDefaultTransactionIsolation(Connection.TRANSACTION_READ_COMMITTED);
    poolableCF.setDefaultAutoCommit(false);
    poolableCF.setRollbackOnReturn(true);

    // Create the actual pool of connections, and apply any properties
    connectionPool = new org.apache.commons.pool2.impl.GenericObjectPool(poolableCF);
    connectionPool.setTestOnBorrow(true);
    connectionPool.setMaxIdle(maxPoolSize);

    connectionPool.setMinIdle(MIN_POOL_SIZE);
    connectionPool.setMaxTotal(maxPoolSize);
    connectionPool.setMaxWaitMillis(8000);
    connectionPool.setMinEvictableIdleTimeMillis((int) TimeUnit.MINUTES.toMillis(30));
    poolableCF.setPool(connectionPool);/* www.  j  a  v a  2s.co  m*/
    DS = new org.apache.commons.dbcp2.PoolingDataSource(connectionPool);
}

From source file:it.cnr.icar.eric.server.persistence.rdb.SQLPersistenceManagerImpl.java

@SuppressWarnings("unused")
private SQLPersistenceManagerImpl() {
    loadUsernamePassword();//  w w  w. jav a2  s  .c  o m
    constructDatabaseURL();

    // define transaction isolation
    if ("TRANSACTION_READ_COMMITTED".equalsIgnoreCase(
            RegistryProperties.getInstance().getProperty("eric.persistence.rdb.transactionIsolation"))) {
        transactionIsolation = Connection.TRANSACTION_READ_COMMITTED;
    } else {
        transactionIsolation = Connection.TRANSACTION_READ_UNCOMMITTED;
    }

    useConnectionPool = Boolean.valueOf(
            RegistryProperties.getInstance().getProperty("eric.persistence.rdb.useConnectionPooling", "true"))
            .booleanValue();
    skipReferenceCheckOnRemove = Boolean.valueOf(RegistryProperties.getInstance()
            .getProperty("eric.persistence.rdb.skipReferenceCheckOnRemove", "false")).booleanValue();
    dumpStackOnQuery = Boolean.valueOf(
            RegistryProperties.getInstance().getProperty("eric.persistence.rdb.dumpStackOnQuery", "false"))
            .booleanValue();
    boolean debugConnectionPool = Boolean
            .valueOf(RegistryProperties.getInstance().getProperty("eric.persistence.rdb.pool.debug", "false"))
            .booleanValue();

    // Create JNDI context
    if (useConnectionPool) {
        if (!debugConnectionPool) {
            // Use Container's connection pooling
            String ericName = RegistryProperties.getInstance().getProperty("eric.name", "eric");
            String envName = "java:comp/env";
            String dataSourceName = "jdbc/" + ericName + "-registry";
            Context ctx = null;

            try {
                ctx = new InitialContext();
                if (null == ctx) {
                    log.info(ServerResourceBundle.getInstance().getString("message.UnableToGetInitialContext"));
                }
            } catch (NamingException e) {
                log.info(ServerResourceBundle.getInstance().getString("message.UnableToGetInitialContext"), e);
                ctx = null;
            }

            if (null != ctx) {
                try {
                    ctx = (Context) ctx.lookup(envName);

                    if (null == ctx) {
                        log.info(ServerResourceBundle.getInstance().getString(
                                "message.UnableToGetJNDIContextForDataSource", new Object[] { envName }));
                    }
                } catch (NamingException e) {
                    log.info(
                            ServerResourceBundle.getInstance().getString(
                                    "message.UnableToGetJNDIContextForDataSource", new Object[] { envName }),
                            e);
                    ctx = null;
                }
            }

            if (null != ctx) {
                try {
                    ds = (DataSource) ctx.lookup(dataSourceName);

                    if (null == ds) {
                        log.info(ServerResourceBundle.getInstance().getString(
                                "message.UnableToGetJNDIContextForDataSource",
                                new Object[] { envName + "/" + dataSourceName }));
                    }
                } catch (NamingException e) {
                    log.info(ServerResourceBundle.getInstance().getString(
                            "message.UnableToGetJNDIContextForDataSource",
                            new Object[] { envName + "/" + dataSourceName }), e);
                    ds = null;
                }
            }

            if (null != ds) {
                // Create a test connection to make sure all is well with
                // DataSource
                Connection connection = null;
                try {
                    connection = ds.getConnection();
                } catch (Exception e) {
                    log.info(ServerResourceBundle.getInstance().getString(
                            "message.UnableToCreateTestConnectionForDataSource",
                            new Object[] { envName + "/" + dataSourceName }), e);
                    ds = null;
                } finally {
                    if (connection != null) {
                        try {
                            connection.close();
                        } catch (Exception e1) {
                            // Do nothing.
                            connection = null;
                        }
                    }
                }
            }
        }

        if (ds == null) {
            // No DataSource available so create our own ConnectionPool
            loadDatabaseDriver();
            createConnectionPool();
        }
    } else {
        loadDatabaseDriver();
    }
}

From source file:com.feedzai.commons.sql.abstraction.engine.impl.OracleEngine.java

/**
 * Overrides {@link com.feedzai.commons.sql.abstraction.engine.AbstractDatabaseEngine#setTransactionIsolation()} This is because
 * Oracle does not support READ_UNCOMMITTED e REPEATABLE_READ.
 *
 * @throws SQLException If a database access error occurs.
 *///www.j a v  a2  s . co m
@Override
protected void setTransactionIsolation() throws SQLException {
    int isolation = properties.getIsolationLevel();

    if (isolation == Connection.TRANSACTION_READ_UNCOMMITTED) {
        isolation = Connection.TRANSACTION_READ_COMMITTED;
    }

    if (isolation == Connection.TRANSACTION_REPEATABLE_READ) {
        isolation = Connection.TRANSACTION_SERIALIZABLE;
    }

    conn.setTransactionIsolation(isolation);
}

From source file:org.spring.data.gemfire.app.dao.provider.JdbcUserDao.java

@Override
public boolean exists(final String id) {
    try {//from  ww w  .  ja v  a2  s.com
        Connection connection = createConnectionBuilder()
                .setTransactionIsolation(Connection.TRANSACTION_READ_COMMITTED).build();

        PreparedStatement statement = connection.prepareStatement(EXISTS_USER_SQL);

        statement.setString(1, id);

        ResultSet resultSet = statement.executeQuery();

        return (resultSet != null && resultSet.next() && resultSet.getInt(1) > 0);
    } catch (SQLException e) {
        throw createDataAccessException(
                String.format("Failed to determine if User identified by (%1$s) exists!", id), e);
    }
}

From source file:org.nuxeo.runtime.datasource.BasicManagedDataSourceFactory.java

/**
 * Creates and configures a {@link BasicManagedDataSource} instance based on
 * the given properties./* w w  w.  j  a v  a 2  s.c  o  m*/
 *
 * @param properties the datasource configuration properties
 * @throws Exception if an error occurs creating the data source
 */
public static DataSource createDataSource(Properties properties) throws Exception {
    BasicManagedDataSource dataSource = new BasicManagedDataSource();

    String value = properties.getProperty(PROP_DEFAULTAUTOCOMMIT);
    if (value != null) {
        dataSource.setDefaultAutoCommit(Boolean.valueOf(value).booleanValue());
    }

    value = properties.getProperty(PROP_DEFAULTREADONLY);
    if (value != null) {
        dataSource.setDefaultReadOnly(Boolean.valueOf(value).booleanValue());
    }

    value = properties.getProperty(PROP_DEFAULTTRANSACTIONISOLATION);
    if (value != null) {
        int level = UNKNOWN_TRANSACTIONISOLATION;
        if ("NONE".equalsIgnoreCase(value)) {
            level = Connection.TRANSACTION_NONE;
        } else if ("READ_COMMITTED".equalsIgnoreCase(value)) {
            level = Connection.TRANSACTION_READ_COMMITTED;
        } else if ("READ_UNCOMMITTED".equalsIgnoreCase(value)) {
            level = Connection.TRANSACTION_READ_UNCOMMITTED;
        } else if ("REPEATABLE_READ".equalsIgnoreCase(value)) {
            level = Connection.TRANSACTION_REPEATABLE_READ;
        } else if ("SERIALIZABLE".equalsIgnoreCase(value)) {
            level = Connection.TRANSACTION_SERIALIZABLE;
        } else {
            try {
                level = Integer.parseInt(value);
            } catch (NumberFormatException e) {
                System.err.println("Could not parse defaultTransactionIsolation: " + value);
                System.err.println("WARNING: defaultTransactionIsolation not set");
                System.err.println("using default value of database driver");
                level = UNKNOWN_TRANSACTIONISOLATION;
            }
        }
        dataSource.setDefaultTransactionIsolation(level);
    }

    value = properties.getProperty(PROP_DEFAULTCATALOG);
    if (value != null) {
        dataSource.setDefaultCatalog(value);
    }

    value = properties.getProperty(PROP_DRIVERCLASSNAME);
    if (value != null) {
        dataSource.setDriverClassName(value);
    }

    value = properties.getProperty(PROP_MAXACTIVE);
    if (value != null) {
        dataSource.setMaxActive(Integer.parseInt(value));
    }

    value = properties.getProperty(PROP_MAXIDLE);
    if (value != null) {
        dataSource.setMaxIdle(Integer.parseInt(value));
    }

    value = properties.getProperty(PROP_MINIDLE);
    if (value != null) {
        dataSource.setMinIdle(Integer.parseInt(value));
    }

    value = properties.getProperty(PROP_INITIALSIZE);
    if (value != null) {
        dataSource.setInitialSize(Integer.parseInt(value));
    }

    value = properties.getProperty(PROP_MAXWAIT);
    if (value != null) {
        dataSource.setMaxWait(Long.parseLong(value));
    }

    value = properties.getProperty(PROP_TESTONBORROW);
    if (value != null) {
        dataSource.setTestOnBorrow(Boolean.valueOf(value).booleanValue());
    }

    value = properties.getProperty(PROP_TESTONRETURN);
    if (value != null) {
        dataSource.setTestOnReturn(Boolean.valueOf(value).booleanValue());
    }

    value = properties.getProperty(PROP_TIMEBETWEENEVICTIONRUNSMILLIS);
    if (value != null) {
        dataSource.setTimeBetweenEvictionRunsMillis(Long.parseLong(value));
    }

    value = properties.getProperty(PROP_NUMTESTSPEREVICTIONRUN);
    if (value != null) {
        dataSource.setNumTestsPerEvictionRun(Integer.parseInt(value));
    }

    value = properties.getProperty(PROP_MINEVICTABLEIDLETIMEMILLIS);
    if (value != null) {
        dataSource.setMinEvictableIdleTimeMillis(Long.parseLong(value));
    }

    value = properties.getProperty(PROP_TESTWHILEIDLE);
    if (value != null) {
        dataSource.setTestWhileIdle(Boolean.valueOf(value).booleanValue());
    }

    value = properties.getProperty(PROP_PASSWORD);
    if (value != null) {
        dataSource.setPassword(value);
    }

    value = properties.getProperty(PROP_URL);
    if (value != null) {
        dataSource.setUrl(value);
    }

    value = properties.getProperty(PROP_USERNAME);
    if (value != null) {
        dataSource.setUsername(value);
    }

    value = properties.getProperty(PROP_VALIDATIONQUERY);
    if (value != null) {
        dataSource.setValidationQuery(value);
    }

    value = properties.getProperty(PROP_VALIDATIONQUERY_TIMEOUT);
    if (value != null) {
        dataSource.setValidationQueryTimeout(Integer.parseInt(value));
    }

    value = properties.getProperty(PROP_ACCESSTOUNDERLYINGCONNECTIONALLOWED);
    if (value != null) {
        dataSource.setAccessToUnderlyingConnectionAllowed(Boolean.valueOf(value).booleanValue());
    }

    value = properties.getProperty(PROP_REMOVEABANDONED);
    if (value != null) {
        dataSource.setRemoveAbandoned(Boolean.valueOf(value).booleanValue());
    }

    value = properties.getProperty(PROP_REMOVEABANDONEDTIMEOUT);
    if (value != null) {
        dataSource.setRemoveAbandonedTimeout(Integer.parseInt(value));
    }

    value = properties.getProperty(PROP_LOGABANDONED);
    if (value != null) {
        dataSource.setLogAbandoned(Boolean.valueOf(value).booleanValue());
    }

    value = properties.getProperty(PROP_POOLPREPAREDSTATEMENTS);
    if (value != null) {
        dataSource.setPoolPreparedStatements(Boolean.valueOf(value).booleanValue());
    }

    value = properties.getProperty(PROP_MAXOPENPREPAREDSTATEMENTS);
    if (value != null) {
        dataSource.setMaxOpenPreparedStatements(Integer.parseInt(value));
    }

    value = properties.getProperty(PROP_INITCONNECTIONSQLS);
    if (value != null) {
        StringTokenizer tokenizer = new StringTokenizer(value, ";");
        dataSource.setConnectionInitSqls(Collections.list(tokenizer));
    }

    value = properties.getProperty(PROP_CONNECTIONPROPERTIES);
    if (value != null) {
        Properties p = getProperties(value);
        Enumeration<?> e = p.propertyNames();
        while (e.hasMoreElements()) {
            String propertyName = (String) e.nextElement();
            dataSource.addConnectionProperty(propertyName, p.getProperty(propertyName));
        }
    }

    // Managed: initialize XADataSource

    value = properties.getProperty(PROP_XADATASOURCE);
    if (value != null) {
        Class<?> xaDataSourceClass;
        try {
            xaDataSourceClass = Class.forName(value);
        } catch (Throwable t) {
            throw (SQLException) new SQLException("Cannot load XA data source class '" + value + "'")
                    .initCause(t);
        }
        XADataSource xaDataSource;
        try {
            xaDataSource = (XADataSource) xaDataSourceClass.newInstance();
        } catch (Throwable t) {
            throw (SQLException) new SQLException("Cannot create XA data source of class '" + value + "'")
                    .initCause(t);
        }
        dataSource.setXaDataSourceInstance(xaDataSource);
    }

    // DBCP-215
    // Trick to make sure that initialSize connections are created
    if (dataSource.getInitialSize() > 0) {
        dataSource.getLogWriter();
    }

    // Return the configured DataSource instance
    return dataSource;
}

From source file:org.cloudgraph.rdb.service.RDBGraphService.java

public DataGraph[] find(Query query, int maxResults) {
    if (query == null)
        throw new IllegalArgumentException("expected non-null 'query' argument");
    validate(query);//from ww  w  .  j a v  a 2 s. c om
    if (log.isDebugEnabled()) {
        log(query);
    }
    Connection con = null;
    try {
        if (log.isDebugEnabled())
            log.debug("getting connection");
        con = ProviderManager.instance().getConnection();
        if (con.getAutoCommit()) {
            if (log.isDebugEnabled())
                log.debug("turning off connection autocommit for graph query");
            con.setAutoCommit(false);
        }

        // TODO: make transaction isolation configurable
        RDBMSVendorName vendor = PlasmaRuntime.getInstance()
                .getRDBMSProviderVendor(DataAccessProviderName.JDBC);
        switch (vendor) {
        case ORACLE:
            con.setTransactionIsolation(Connection.TRANSACTION_READ_COMMITTED);
            break;
        case MYSQL:
            con.setTransactionIsolation(Connection.TRANSACTION_READ_COMMITTED);
            break;
        default:
        }
        if (log.isDebugEnabled())
            log.debug(
                    "using transaction isolation level " + con.getTransactionIsolation() + " for graph query");
    } catch (SQLException e2) {
        if (con != null)
            try {
                if (log.isDebugEnabled())
                    log.debug("closing connection");
                con.close();
            } catch (SQLException e) {
                log.error(e.getMessage(), e);
            }
        throw new DataAccessException(e2);
    }
    GraphQuery dispatcher = new GraphQuery(con);
    try {
        DataGraph[] results = null;

        if (maxResults > 0)
            results = dispatcher.find(query, maxResults, new Timestamp((new Date()).getTime()));
        else
            results = dispatcher.find(query, new Timestamp((new Date()).getTime()));
        return results;
    } finally {
        if (con != null)
            try {
                if (log.isDebugEnabled())
                    log.debug("closing connection");
                con.close();
            } catch (SQLException e) {
                log.error(e.getMessage(), e);
            }
    }
}