Example usage for java.sql Connection TRANSACTION_READ_UNCOMMITTED

List of usage examples for java.sql Connection TRANSACTION_READ_UNCOMMITTED

Introduction

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

Prototype

int TRANSACTION_READ_UNCOMMITTED

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

Click Source Link

Document

A constant indicating that dirty reads, non-repeatable reads and phantom reads can occur.

Usage

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

/**
 * Creates and configures a {@link BasicManagedDataSource} instance based on
 * the given properties./*www .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.openanzo.datasource.nodecentric.internal.NodeCentricDatasource.java

/**
 * Initialize a jdbc connection pool/*from  w  w w . j  av a2 s.  c  om*/
 * 
 * @param type
 *            either rw or query pool
 * @param maxActive
 *            maximum number of connections in pool
 * @param configuration
 *            configuration properties used for creating database connections
 * @return connection pool
 * @throws AnzoException
 *             {@link ExceptionConstants#RDB.DRIVER_NAME} if there was a problem loading class for database driver
 */
private GenericObjectPool initializeConnectionFactory(boolean write, int maxActive) throws AnzoException {
    // Will use in jndi
    // DataSource ds = (DataSource) ctx.lookup(RepositoryProperties.getDatabaseJndiName(properties));
    try {
        Class.forName(configuration.getDriverClassName());
    } catch (ClassNotFoundException e1) {
        throw new AnzoException(ExceptionConstants.RDB.DRIVER_NAME, e1, configuration.getDriverClassName());
    }
    Properties props = new Properties();
    props.put("user", configuration.getUser());
    props.put("password", configuration.getPassword());
    props.put("SetBigStringTryClob", "true");
    ConnectionFactory connectionFactory = new DriverManagerConnectionFactory(configuration.getJdbcUrl(), props);
    GenericObjectPool connectionPool = new GenericObjectPool();
    connectionPool.setMaxActive(maxActive);
    connectionPool.setMaxIdle(Math.max(1, maxActive / 2));
    connectionPool.setMinIdle(0);
    connectionPool.setMinEvictableIdleTimeMillis(1000 * 60 * 10);
    connectionPool.setTimeBetweenEvictionRunsMillis(1000 * 60 * 10);
    connectionPool.setWhenExhaustedAction(GenericObjectPool.WHEN_EXHAUSTED_BLOCK);
    connectionPool.setMaxWait(GenericKeyedObjectPool.DEFAULT_MAX_WAIT);
    connectionPool.setTestOnBorrow(true);
    GenericKeyedObjectPoolFactory statementPool = new GenericKeyedObjectPoolFactory(null, PS_CACHE_SIZE,
            GenericKeyedObjectPool.WHEN_EXHAUSTED_BLOCK, GenericKeyedObjectPool.DEFAULT_MAX_WAIT, PS_CACHE_SIZE,
            PS_CACHE_SIZE, GenericKeyedObjectPool.DEFAULT_TEST_ON_BORROW,
            GenericKeyedObjectPool.DEFAULT_TEST_ON_RETURN,
            GenericKeyedObjectPool.DEFAULT_TIME_BETWEEN_EVICTION_RUNS_MILLIS,
            GenericKeyedObjectPool.DEFAULT_NUM_TESTS_PER_EVICTION_RUN,
            GenericKeyedObjectPool.DEFAULT_MIN_EVICTABLE_IDLE_TIME_MILLIS,
            GenericKeyedObjectPool.DEFAULT_TEST_WHILE_IDLE);
    PoolableConnectionFactory pcf = new PoolableConnectionFactory(connectionFactory, connectionPool,
            statementPool, configuration.getValidationQuery(), false, true) {
        @Override
        public synchronized Object makeObject() throws Exception {
            Connection connection = (Connection) super.makeObject();
            initializeConnection(connection);
            return connection;
        }
    };

    if (configuration.getSupportsIsolation() && write)
        pcf.setDefaultTransactionIsolation(Connection.TRANSACTION_READ_UNCOMMITTED);
    else if (configuration.getSupportsIsolation() && !write)
        pcf.setDefaultTransactionIsolation(Connection.TRANSACTION_READ_UNCOMMITTED);
    return connectionPool;
}

From source file:org.openanzo.jdbc.container.RDBQuadStoreFactory.java

private PoolableConnectionFactory initializeConnectionFactory(boolean write, int maxActive,
        CoreDBConfiguration configuration) {
    // Will use in jndi
    // DataSource ds = (DataSource) ctx.lookup(RepositoryProperties.getDatabaseJndiName(properties));
    try {//from  ww w  . j ava 2  s  .  co  m
        Class.forName(configuration.getDriverClassName());
    } catch (ClassNotFoundException e1) {
        throw new AnzoRuntimeException(ExceptionConstants.RDB.DRIVER_NAME, e1,
                configuration.getDriverClassName());
    }
    ConnectionFactory connectionFactory = new DriverManagerConnectionFactory(configuration.getJdbcUrl(),
            configuration.getUser(), configuration.getPassword());
    connectionPool = new GenericObjectPool();
    connectionPool.setMaxActive(maxActive);
    connectionPool.setMinIdle(1);
    connectionPool.setWhenExhaustedAction(GenericObjectPool.WHEN_EXHAUSTED_BLOCK);
    connectionPool.setMaxWait(30000);
    connectionPool.setMaxActive(maxActive);
    pcf = new PoolableConnectionFactory(connectionFactory, connectionPool, null, null, false, true);
    if ((!write && configuration.getSupportsIsolation()))
        pcf.setDefaultTransactionIsolation(Connection.TRANSACTION_READ_UNCOMMITTED);
    return pcf;
}

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

public final void setInitialTransactionIsolation(int level) {
    if (level != Connection.TRANSACTION_READ_UNCOMMITTED && level != Connection.TRANSACTION_READ_COMMITTED
            && level != Connection.TRANSACTION_REPEATABLE_READ && level != Connection.TRANSACTION_SERIALIZABLE)
        throw new IllegalArgumentException("Invalid value :" + level);
    synchronized (this) {
        if (this.txIsolation != level) {
            this.txIsolation = level;
            // perhaps do like setInitialSchema() : i.e. call setTransactionIsolation() on
            // existing connections
            this.invalidateAllConnections(false);
        }/*from   w  w  w.ja v a2 s  .  c  o  m*/
    }
}

From source file:org.openmrs.module.dataimporttool.dmt.dao.DAOFactory.java

/**
 * This method creates a DAO based on the type of DS
 * @param ds// w  ww  .ja  va  2 s  .  c o m
 * @return
 * @throws SystemException
 */
private DatabaseUtil createDAOs(final DataImportTool dit, DAOTypes type) throws SystemException {
    // create connections DataImportTool Entity object.
    if (dit == null) {
        throw new SystemException("The datasource info doesn't exist in entity object");
    }

    if (type == DAOTypes.TARGET) { //only for target data source

        try {
            Session session = Context.getService(DataImportToolService.class).getDao().getSessionFactory()
                    .openSession();
            connection = session.connection();
            connection.setAutoCommit(false);// disable auto-commit
            connection.setTransactionIsolation(Connection.TRANSACTION_READ_UNCOMMITTED);

            connection = DriverManager.getConnection(dit.getLeftDbLocation() + dit.getLeftDbName(),
                    dit.getLeftUserName(), dit.getLeftPassword());

            if (connection != null)
                return new DatabaseUtil(connection);

        } catch (Exception e) {
            e.printStackTrace();
        } //end try - catch blog

    } else {

        try {
            Session session = Context.getService(DataImportToolService.class).getDao().getSessionFactory()
                    .openSession();
            connection = session.connection();
            connection = DriverManager.getConnection(dit.getRightDbLocation() + dit.getRightDbName(),
                    dit.getRightUserName(), dit.getRightPassword());

            if (connection != null)
                return new DatabaseUtil(connection);

        } catch (Exception e) {
            e.printStackTrace();
        } //end try-catch blog
    }

    return null;
}

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();/*w w  w .  j  ava 2  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 . jav  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.sakaiproject.tomcat.jdbc.pool.SakaiBasicDataSource.java

/**
 * Set the default transaction isolation level from a string value, based on the settings and values in java.sql.Connection
 * //www. jav a 2  s  . c  o  m
 * @param defaultTransactionIsolation
 */
public void setDefaultTransactionIsolationString(String defaultTransactionIsolation) {
    if ((defaultTransactionIsolation == null) || (defaultTransactionIsolation.trim().length() == 0)) {
        setDefaultTransactionIsolation(DataSourceFactory.UNKNOWN_TRANSACTIONISOLATION);
    } else if (defaultTransactionIsolation.trim().equalsIgnoreCase("TRANSACTION_NONE")) {
        setDefaultTransactionIsolation(Connection.TRANSACTION_NONE);
    } else if (defaultTransactionIsolation.trim().equalsIgnoreCase("TRANSACTION_READ_UNCOMMITTED")) {
        setDefaultTransactionIsolation(Connection.TRANSACTION_READ_UNCOMMITTED);
    } else if (defaultTransactionIsolation.trim().equalsIgnoreCase("TRANSACTION_READ_COMMITTED")) {
        setDefaultTransactionIsolation(Connection.TRANSACTION_READ_COMMITTED);
    } else if (defaultTransactionIsolation.trim().equalsIgnoreCase("TRANSACTION_REPEATABLE_READ")) {
        setDefaultTransactionIsolation(Connection.TRANSACTION_REPEATABLE_READ);
    } else if (defaultTransactionIsolation.trim().equalsIgnoreCase("TRANSACTION_SERIALIZABLE")) {
        setDefaultTransactionIsolation(Connection.TRANSACTION_SERIALIZABLE);
    } else {
        setDefaultTransactionIsolation(DataSourceFactory.UNKNOWN_TRANSACTIONISOLATION);
        M_log.warn("invalid transaction isolation level: " + defaultTransactionIsolation);
    }
}

From source file:org.sonar.db.version.BaseDataChange.java

/**
 * Do not forget to close it !/*from w  ww  . j  ava  2  s  . co m*/
 */
protected Connection openConnection() throws SQLException {
    Connection connection = db.getDataSource().getConnection();
    connection.setAutoCommit(false);
    if (connection.getMetaData().supportsTransactionIsolationLevel(Connection.TRANSACTION_READ_UNCOMMITTED)) {
        connection.setTransactionIsolation(Connection.TRANSACTION_READ_UNCOMMITTED);
    }
    return connection;
}

From source file:org.sonar.server.db.migrations.BaseDataChange.java

@Override
public final void execute() throws SQLException {
    Connection readConnection = null, writeConnection = null;
    try {//from www.  j a  v  a 2 s.co  m
        readConnection = db.getDataSource().getConnection();
        readConnection.setAutoCommit(false);
        if (readConnection.getMetaData()
                .supportsTransactionIsolationLevel(Connection.TRANSACTION_READ_UNCOMMITTED)) {
            readConnection.setTransactionIsolation(Connection.TRANSACTION_READ_UNCOMMITTED);
        }

        writeConnection = db.getDataSource().getConnection();
        writeConnection.setAutoCommit(false);
        Context context = new Context(db, readConnection, writeConnection);
        execute(context);

    } finally {
        DbUtils.closeQuietly(readConnection);
        DbUtils.closeQuietly(writeConnection);
    }
}