Example usage for org.apache.commons.dbcp2 BasicDataSource setDefaultAutoCommit

List of usage examples for org.apache.commons.dbcp2 BasicDataSource setDefaultAutoCommit

Introduction

In this page you can find the example usage for org.apache.commons.dbcp2 BasicDataSource setDefaultAutoCommit.

Prototype

public void setDefaultAutoCommit(Boolean defaultAutoCommit) 

Source Link

Document

Sets default auto-commit state of connections returned by this datasource.

Note: this method currently has no effect once the pool has been initialized.

Usage

From source file:com.github.akiraly.db4j.pool.DbcpUtils.java

public static BasicDataSource newDefaultDS() {
    BasicDataSource dataSource = new BasicDataSource();
    dataSource.setDefaultAutoCommit(false);

    dataSource.setDefaultQueryTimeout(1);
    dataSource.setValidationQueryTimeout(1);
    dataSource.setMaxWaitMillis(5000);/*from  w ww.  j a va 2  s. co  m*/

    dataSource.setDefaultTransactionIsolation(Connection.TRANSACTION_READ_COMMITTED);

    dataSource.setInitialSize(4);
    dataSource.setMinIdle(4);
    dataSource.setMaxIdle(8);
    dataSource.setMaxTotal(16);
    dataSource.setPoolPreparedStatements(true);
    dataSource.setMaxOpenPreparedStatements(128);
    return dataSource;
}

From source file:net.cloudkit.enterprises.infrastructure.configuration.ApplicationConfiguration.java

@Bean(initMethod = "init", destroyMethod = "close")
public DataSource dataSource() {
    BasicDataSource basicDataSource = new BasicDataSource();
    basicDataSource.setDriverClassName(driverClassName);
    basicDataSource.setUrl(url);/*w w w . j  ava  2 s .  co  m*/
    basicDataSource.setUsername(username);
    basicDataSource.setPassword(password);
    basicDataSource.setDefaultAutoCommit(false);
    return basicDataSource;
}

From source file:com.graphaware.importer.data.access.DbDataReader.java

/**
 * Create a {@link javax.sql.DataSource} used for talking to the database.
 *
 * @return data source.//from w w w  . java  2s  .  co m
 */
protected DataSource createDataSource() {
    BasicDataSource dataSource = new BasicDataSource();

    dataSource.setUrl(getUrl(dbHost, dbPort));
    dataSource.setUsername(user);
    dataSource.setPassword(password);
    dataSource.setDefaultReadOnly(true);
    dataSource.setDefaultAutoCommit(false);

    dataSource.setDriverClassName(getDriverClassName());

    additionalConfig(dataSource);

    return dataSource;
}

From source file:com.alehuo.wepas2016projekti.configuration.ProductionConfiguration.java

/**
 * Heroku -palvelussa kytetn PostgreSQL -tietokantaa tiedon
 * tallentamiseen. Tm metodi hakee herokusta tietokantayhteyden
 * mahdollistavat ympristmuuttujat./*from   www  .  ja v  a  2s .  c  o m*/
 *
 * @return @throws URISyntaxException
 */
@Bean
public BasicDataSource dataSource() throws URISyntaxException {
    URI dbUri = new URI(System.getenv("DATABASE_URL"));

    String username = dbUri.getUserInfo().split(":")[0];
    String password = dbUri.getUserInfo().split(":")[1];
    String dbUrl = "jdbc:postgresql://" + dbUri.getHost() + ':' + dbUri.getPort() + dbUri.getPath();

    BasicDataSource basicDataSource = new BasicDataSource();
    basicDataSource.setUrl(dbUrl);
    basicDataSource.setUsername(username);
    basicDataSource.setPassword(password);

    //Autocommit pois plt
    basicDataSource.setDefaultAutoCommit(false);

    return basicDataSource;
}

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

private void setupDBCP2basic() throws SQLException {
    BasicDataSource ds = new BasicDataSource();
    ds.setDriverClassName(dbDriver);/*from   w  w  w .ja  v  a  2  s.co m*/
    ds.setUsername("sa");
    ds.setPassword("");
    ds.setUrl(jdbcURL);
    ds.setMaxTotal(maxPoolSize);
    ds.setDefaultAutoCommit(false);
    ds.setDefaultTransactionIsolation(Connection.TRANSACTION_READ_COMMITTED);

    ds.getConnection().createStatement().execute("CREATE TABLE IF NOT EXISTS test (column varchar);");
    DS = ds;
}

From source file:com.samovich.service.blueprint.App.java

/**
 * Data source configuration with dbcp/*from   w  w  w. j a  va2 s  .c o  m*/
 * @return dataSource
 */
@Bean
public DataSource dataSource() {
    BasicDataSource dataSource = new BasicDataSource();
    dataSource.setDriverClassName("com.mysql.jdbc.Driver");
    dataSource.setUrl("jdbc:mysql://HOST:PORT/DATABASE_NAME");
    dataSource.setUsername("DB_USER");
    dataSource.setPassword("RB_PW");
    dataSource.setValidationQuery("select 1");
    dataSource.setMaxTotal(50);
    dataSource.setTestOnBorrow(true);
    dataSource.setMaxWaitMillis(10000);
    dataSource.setRemoveAbandonedOnBorrow(true);
    dataSource.setDefaultAutoCommit(false);
    dataSource.setNumTestsPerEvictionRun(3);
    dataSource.setTimeBetweenEvictionRunsMillis(1800000);
    dataSource.setMinEvictableIdleTimeMillis(1800000);
    return dataSource;
}

From source file:net.gcolin.simplerepo.search.SearchController.java

public SearchController(ConfigurationManager configManager) throws IOException {
    this.configManager = configManager;
    File plugins = new File(configManager.getRoot(), "plugins");
    plugins.mkdirs();//w  ww  . ja  va2 s  . co m
    System.setProperty("derby.system.home", plugins.getAbsolutePath());
    BasicDataSource s = new BasicDataSource();
    s.setDriverClassName("org.apache.derby.jdbc.EmbeddedDriver");
    s.setUrl("jdbc:derby:search" + (new File(plugins, "search").exists() ? "" : ";create=true"));
    s.setUsername("su");
    s.setPassword("");
    s.setMaxTotal(10);
    s.setMinIdle(0);
    s.setDefaultAutoCommit(true);
    datasource = s;

    Set<String> allTables = new HashSet<>();
    Connection connection = null;

    try {
        try {
            connection = datasource.getConnection();
            connection.setAutoCommit(false);
            DatabaseMetaData dbmeta = connection.getMetaData();
            try (ResultSet rs = dbmeta.getTables(null, null, null, new String[] { "TABLE" })) {
                while (rs.next()) {
                    allTables.add(rs.getString("TABLE_NAME").toLowerCase());
                }
            }

            if (!allTables.contains("artifact")) {
                QueryRunner run = new QueryRunner();
                run.update(connection,
                        "CREATE TABLE artifactindex(artifact bigint NOT NULL, version bigint NOT NULL)");
                run.update(connection, "INSERT INTO artifactindex (artifact,version) VALUES (?,?)", 1L, 1L);
                run.update(connection,
                        "CREATE TABLE artifact(id bigint NOT NULL,groupId character varying(120), artifactId character varying(120),CONSTRAINT artifact_pkey PRIMARY KEY (id))");
                run.update(connection,
                        "CREATE TABLE artifactversion(artifact_id bigint NOT NULL,id bigint NOT NULL,"
                                + "version character varying(100)," + "reponame character varying(30),"
                                + "CONSTRAINT artifactversion_pkey PRIMARY KEY (id),"
                                + "CONSTRAINT fk_artifactversion_artifact_id FOREIGN KEY (artifact_id) REFERENCES artifact (id) )");
                run.update(connection,
                        "CREATE TABLE artifacttype(version_id bigint NOT NULL,packaging character varying(20) NOT NULL,classifier character varying(30),"
                                + "CONSTRAINT artifacttype_pkey PRIMARY KEY (version_id,packaging,classifier),"
                                + "CONSTRAINT fk_artifacttype_version FOREIGN KEY (version_id) REFERENCES artifactversion (id))");
                run.update(connection, "CREATE INDEX artifactindex ON artifact(groupId,artifactId)");
                run.update(connection, "CREATE INDEX artifactgroupindex ON artifact(groupId)");
                run.update(connection, "CREATE INDEX artifactversionindex ON artifactversion(version)");
            }
            connection.commit();
        } catch (SQLException ex) {
            connection.rollback();
            throw ex;
        } finally {
            DbUtils.close(connection);
        }
    } catch (SQLException ex) {
        throw new IOException(ex);
    }
}

From source file:com.norconex.collector.core.data.store.impl.jdbc.JDBCCrawlDataStore.java

private DataSource createDataSource(String dbDir) {
    BasicDataSource ds = new BasicDataSource();
    if (database == Database.DERBY) {
        ds.setDriverClassName("org.apache.derby.jdbc.EmbeddedDriver");
        ds.setUrl("jdbc:derby:" + dbDir + ";create=true");
    } else {//from   ww w  .jav a 2 s. co  m
        ds.setDriverClassName("org.h2.Driver");
        ds.setUrl("jdbc:h2:" + dbDir + ";WRITE_DELAY=0;AUTOCOMMIT=ON");
    }
    ds.setDefaultAutoCommit(true);
    return ds;
}

From source file:de.micromata.genome.util.runtime.LocalSettingsEnv.java

/**
 * Parses the ds.//from   w ww. j  a v a 2s  .  c  o  m
 */
protected void parseDs() {
    // db.ds.rogerdb.name=RogersOracle
    // db.ds.rogerdb.drivername=oracle.jdbc.driver.OracleDriver
    // db.ds.rogerdb.url=jdbc:oracle:thin:@localhost:1521:rogdb
    // db.ds.rogerdb.username=genome
    // db.ds.rogerdb.password=genome
    List<String> dse = localSettings.getKeysPrefixWithInfix("db.ds", "name");
    for (String dsn : dse) {
        String key = dsn + ".name";
        String name = localSettings.get(key);
        if (StringUtils.isBlank(name) == true) {
            log.error("Name in local-settings is not defined with key: " + key);
            continue;
        }
        key = dsn + ".drivername";
        String driverName = localSettings.get(key);
        if (StringUtils.isBlank(name) == true) {
            log.error("drivername in local-settings is not defined with key: " + key);
            continue;
        }
        key = dsn + ".url";
        String url = localSettings.get(key);
        if (StringUtils.isBlank(name) == true) {
            log.error("url in local-settings is not defined with key: " + key);
            continue;
        }
        key = dsn + ".username";
        String userName = localSettings.get(key);
        key = dsn + ".password";
        String password = localSettings.get(key);
        BasicDataSource bd = dataSourceSuplier.get();

        bd.setDriverClassName(driverName);
        bd.setUrl(url);
        bd.setUsername(userName);
        bd.setPassword(password);
        bd.setMaxTotal(localSettings.getIntValue(dsn + ".maxActive",
                GenericKeyedObjectPoolConfig.DEFAULT_MAX_TOTAL_PER_KEY));
        bd.setMaxIdle(localSettings.getIntValue(dsn + ".maxIdle",
                GenericKeyedObjectPoolConfig.DEFAULT_MAX_IDLE_PER_KEY));
        bd.setMinIdle(localSettings.getIntValue(dsn + ".minIdle",
                GenericKeyedObjectPoolConfig.DEFAULT_MIN_IDLE_PER_KEY));
        bd.setMaxWaitMillis(localSettings.getLongValue(dsn + ".maxWait",
                GenericKeyedObjectPoolConfig.DEFAULT_MAX_WAIT_MILLIS));
        bd.setInitialSize(localSettings.getIntValue(dsn + ".intialSize", 0));
        bd.setDefaultCatalog(localSettings.get(dsn + ".defaultCatalog", null));
        bd.setDefaultAutoCommit(localSettings.getBooleanValue(dsn + ".defaultAutoCommit", true));
        bd.setValidationQuery(localSettings.get(dsn + ".validationQuery", null));
        bd.setValidationQueryTimeout(localSettings.getIntValue(dsn + ".validationQueryTimeout", -1));
        dataSources.put(name, bd);
    }
}

From source file:org.apache.jmeter.protocol.jdbc.config.DataSourceElement.java

private BasicDataSource initPool(String maxPool) {
    BasicDataSource dataSource = new BasicDataSource();

    if (log.isDebugEnabled()) {
        StringBuilder sb = new StringBuilder(40);
        sb.append("MaxPool: ");
        sb.append(maxPool);//from w  w w  . jav  a2 s  . c  o m
        sb.append(" Timeout: ");
        sb.append(getTimeout());
        sb.append(" TrimInt: ");
        sb.append(getTrimInterval());
        sb.append(" Auto-Commit: ");
        sb.append(isAutocommit());
        log.debug(sb.toString());
    }
    int poolSize = Integer.parseInt(maxPool);
    dataSource.setMinIdle(0);
    dataSource.setInitialSize(poolSize);
    dataSource.setMaxIdle(poolSize);
    dataSource.setMaxTotal(poolSize);
    dataSource.setMaxWaitMillis(Long.parseLong(getTimeout()));

    dataSource.setDefaultAutoCommit(Boolean.valueOf(isAutocommit()));

    if (log.isDebugEnabled()) {
        StringBuilder sb = new StringBuilder(40);
        sb.append("KeepAlive: ");
        sb.append(isKeepAlive());
        sb.append(" Age: ");
        sb.append(getConnectionAge());
        sb.append(" CheckQuery: ");
        sb.append(getCheckQuery());
        log.debug(sb.toString());
    }
    dataSource.setTestOnBorrow(false);
    dataSource.setTestOnReturn(false);
    dataSource.setTestOnCreate(false);
    dataSource.setTestWhileIdle(false);

    if (isKeepAlive()) {
        dataSource.setTestWhileIdle(true);
        dataSource.setValidationQuery(getCheckQuery());
        dataSource.setSoftMinEvictableIdleTimeMillis(Long.parseLong(getConnectionAge()));
        dataSource.setTimeBetweenEvictionRunsMillis(Integer.parseInt(getTrimInterval()));
    }

    int transactionIsolation = DataSourceElementBeanInfo.getTransactionIsolationMode(getTransactionIsolation());
    if (transactionIsolation >= 0) {
        dataSource.setDefaultTransactionIsolation(transactionIsolation);
    }

    String _username = getUsername();
    if (log.isDebugEnabled()) {
        StringBuilder sb = new StringBuilder(40);
        sb.append("Driver: ");
        sb.append(getDriver());
        sb.append(" DbUrl: ");
        sb.append(getDbUrl());
        sb.append(" User: ");
        sb.append(_username);
        log.debug(sb.toString());
    }
    dataSource.setDriverClassName(getDriver());
    dataSource.setUrl(getDbUrl());

    if (_username.length() > 0) {
        dataSource.setUsername(_username);
        dataSource.setPassword(getPassword());
    }

    // log is required to ensure errors are available
    //source.enableLogging(new LogKitLogger(log));
    if (log.isDebugEnabled()) {
        log.debug("PoolConfiguration:" + this.dataSource);
    }
    return dataSource;
}