Example usage for java.sql Connection setAutoCommit

List of usage examples for java.sql Connection setAutoCommit

Introduction

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

Prototype

void setAutoCommit(boolean autoCommit) throws SQLException;

Source Link

Document

Sets this connection's auto-commit mode to the given state.

Usage

From source file:com.csc.fsg.life.dao.bo.AbstractBusinessObjectHandler.java

/**
   Called to handle a command. //  w  w  w. ja va2 s  .co m
   Wraps the {@link #handle(AbstractBusinessObject, BusinessObjectCommand, Connection)} 
   method by creating a connection and ensuring the connection is closed.
   @param dataSource the dataSource.
   @throws BusinessObjectException If there is a business error with the command.
   @throws SQLException If there is an I/O error with the command.
**/
public void handle(DataSource dataSource) throws BusinessObjectException, SQLException {

    Connection conn = null;

    try {
        conn = dataSource.getConnection();

        // turn auto-commit off
        conn.setAutoCommit(false);

        // call the concrete classes handle method
        handle(bo, command, conn);

        // since we are successful, commit the transaction
        conn.commit();
    } catch (SQLException e) {
        if (conn != null)
            conn.rollback();
        throw new SQLException(exceptionHandler.getReadableMessage(e));
    } catch (BusinessObjectException e) {
        if (conn != null)
            conn.rollback();
        throw new BusinessObjectException(exceptionHandler.getReadableMessage(e));
    } catch (Exception e) {
        if (conn != null)
            conn.rollback();
        throw new BusinessObjectException(exceptionHandler.getReadableMessage(e));
    } finally {
        try {
            if (conn != null)
                conn.close();
        } catch (Exception cme) {
            logger.error("Connection close exception: " + cme.getMessage());
        }
    }

}

From source file:com.glaf.core.execution.FileExecutionHelper.java

public void createTable(Connection connection) {
    boolean autoCommit = false;
    try {/*from ww  w  .j a  va  2s  .c  o m*/
        autoCommit = connection.getAutoCommit();
        connection.setAutoCommit(false);
        TableDefinition tableDefinition = BlobItemDomainFactory.getTableDefinition();
        if (!DBUtils.tableExists(connection, BlobItemDomainFactory.TABLENAME)) {
            DBUtils.createTable(connection, tableDefinition);
        } else {
            DBUtils.alterTable(connection, tableDefinition);
        }
        connection.commit();
        connection.setAutoCommit(autoCommit);
    } catch (Exception ex) {
        logger.error(ex);
        ex.printStackTrace();
        throw new RuntimeException(ex);
    }
}

From source file:com.agiletec.aps.system.services.authorization.AuthorizationDAO.java

protected void addUpdateUserAuthorizations(String username, List<Authorization> authorizations,
        boolean update) {
    Connection conn = null;
    try {//from www  . j  a  v  a2 s .  c  om
        conn = this.getConnection();
        conn.setAutoCommit(false);
        if (update) {
            super.executeQueryWithoutResultset(conn, DELETE_USER_AUTHORIZATIONS, username);
        }
        this.addUserAuthorizations(username, authorizations, conn);
        conn.commit();
    } catch (Throwable t) {
        this.executeRollback(conn);
        _logger.error("Error detected while addind user authorizations", t);
        throw new RuntimeException("Error detected while addind user authorizations", t);
    } finally {
        this.closeConnection(conn);
    }
}

From source file:iudex.da.ContentUpdater.java

/**
 * Update first any content REFERENCES and then the content itself.
 *//*from  w w w. j a  v a 2 s.  c om*/
public void update(UniMap content) throws SQLException {
    Connection conn = dataSource().getConnection();
    try {
        conn.setAutoCommit(false);
        conn.setTransactionIsolation(Connection.TRANSACTION_READ_COMMITTED);
        //FIXME: Correct isolation?

        List<UniMap> refs = content.get(ContentKeys.REFERENCES);
        if (refs != null) {
            update(refs, conn);
        }

        UniMap referer = content.get(ContentKeys.REFERER);
        if (referer != null) {
            //FIXME: Really sufficient as same path as content?
            update(referer, conn);
        }

        update(content, conn);

        conn.commit();
    } finally {
        if (conn != null)
            conn.close();
    }
}

From source file:net.riezebos.thoth.configuration.persistence.ThothDB.java

public Connection getConnection() throws SQLException {
    Properties properties = new Properties();
    String databaseUrl = getConfiguration().getDatabaseUrl();
    if (isEmbedded()) {
        properties.put("databaseName", databaseUrl);
        properties.put("create", "true");
        databaseUrl = "jdbc:derby:";
    }//ww  w .j  a v  a2  s. co  m
    properties.put("user", getConfiguration().getDatabaseUser());
    properties.put("password", getConfiguration().getDatabasePassword());

    Connection connection = DriverManager.getConnection(databaseUrl, properties);
    connection.setAutoCommit(false);
    return new ConnectionWrapper(connection);
}

From source file:net.firejack.platform.core.config.upgrader.SchemaUpgrader.java

/**
 * This method update database package version and increase version number
 *
 * @param packageLookup - Openflame Package lookup
 * @param version       - database version
 * @return version// ww  w  .  j  a v  a  2  s  .c  om
 */
private Version updateDatabaseVersion(String packageLookup, Version version) {
    try {
        Connection connection = dataSource.getConnection();
        try {
            connection.setAutoCommit(true);

            Statement statement = connection.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,
                    ResultSet.CONCUR_UPDATABLE);
            statement.addBatch("UPDATE opf_registry_node SET database_version = " + version.getToVersion() + " "
                    + "WHERE lookup = '" + packageLookup + "';");
            try {
                statement.executeBatch();
                return new Version(version.getToVersion());
            } finally {
                JdbcUtils.closeStatement(statement);
            }
        } finally {
            connection.setAutoCommit(false);
            JdbcUtils.closeConnection(connection);
        }
    } catch (SQLException e) {
        throw new RuntimeException(e);
    }
}

From source file:namedatabasescraper.PageScraper.java

public void storeToDb(MainWindow parent) throws SQLException {
    logger.log(Level.INFO, "Started storing names for scraper id {0}", this.dirname);
    Connection conn = NameDatabaseScraper.application.getConnection();
    PreparedStatement stmt2 = conn.prepareStatement("INSERT INTO names VALUES (?, ?)");
    stmt2.setString(2, this.dirname);
    conn.setAutoCommit(false);
    for (String name : this.names) {
        stmt2.setString(1, name);//from   w ww.j a  va 2  s. c o  m
        stmt2.addBatch();
    }
    stmt2.executeBatch();
    conn.setAutoCommit(true);
    logger.log(Level.INFO, "Stored " + this.names.size() + " names for scraper id {0}", this.dirname);
}

From source file:eagle.storage.jdbc.entity.impl.JdbcEntityWriterImpl.java

@Override
public List<String> write(List<E> entities) throws Exception {
    List<String> keys = new ArrayList<String>();
    if (LOG.isDebugEnabled())
        LOG.debug("Writing " + entities.size() + " entities");
    StopWatch stopWatch = new StopWatch();
    stopWatch.start();//from w w w  .  j  av  a 2s .  co m
    Connection connection = ConnectionManagerFactory.getInstance().getConnection();
    // set auto commit false and commit by hands for 3x~5x better performance
    connection.setAutoCommit(false);

    try {
        TorqueStatementPeerImpl<E> peer = connectionManager
                .getStatementExecutor(this.jdbcEntityDefinition.getJdbcTableName());
        for (E entity : entities) {
            entity.setEncodedRowkey(peer.getPrimaryKeyBuilder().build(entity));
            ColumnValues columnValues = JdbcEntitySerDeserHelper.buildColumnValues(entity,
                    this.jdbcEntityDefinition);

            // TODO: implement batch insert for better performance
            ObjectKey key = peer.delegate().doInsert(columnValues, connection);

            try {
                if (key != null) {
                    keys.add((String) key.getValue());
                } else {
                    keys.add(entity.getEncodedRowkey());
                }
            } catch (ClassCastException ex) {
                throw new RuntimeException(
                        "Key is not in type of String (VARCHAR) , but JdbcType (java.sql.Types): "
                                + key.getJdbcType() + ", value: " + key.getValue(),
                        ex);
            }
        }

        // Why not commit in finally: give up all if any single entity throws exception to make sure consistency guarantee
        if (LOG.isDebugEnabled()) {
            LOG.debug("Committing writing");
        }
        connection.commit();
    } catch (Exception ex) {
        LOG.error("Failed to write records, rolling back", ex);
        connection.rollback();
        throw ex;
    } finally {
        stopWatch.stop();
        if (LOG.isDebugEnabled())
            LOG.debug("Closing connection");
        connection.close();
    }

    LOG.info(String.format("Wrote %s records in %s ms (table: %s)", keys.size(), stopWatch.getTime(),
            this.jdbcEntityDefinition.getJdbcTableName()));
    return keys;
}

From source file:com.mmnaseri.dragonfly.dialect.impl.Mysql5Dialect.java

private synchronized void initializeGenerator(DataAccessSession session,
        TableMetadata<?> generatorTableMetadata, String valueGenerator) {
    final Connection connection = session.getConnection();
    try {/*from  w w  w  . j ava  2 s  . c  o  m*/
        connection.setAutoCommit(false);
        final Statement statement = connection.createStatement();
        final String update = "INSERT IGNORE INTO "
                + DatabaseUtils.qualifyTable(generatorTableMetadata, session.getDatabaseDialect())
                + " (`name`, `value`) VALUES(\"" + DatabaseUtils.escapeString(valueGenerator,
                        session.getDatabaseDialect().getStringEscapeCharacter())
                + "\", 0);";
        log.trace("Initializing generator: " + update);
        statement.executeUpdate(update);
        statement.close();
        connection.commit();
        connection.close();
    } catch (SQLException e) {
        throw new UnsuccessfulOperationError("Failed to initialize generator: " + valueGenerator, e);
    }
}

From source file:net.firejack.platform.core.config.upgrader.SchemaUpgrader.java

/**
 * This method returns current package version by package lookup
 *
 * @param packageLookup//w  w  w. j  a v  a 2s.  c  o  m
 * @return version
 */
private Version getDatabaseVersion(String packageLookup) {
    try {
        Connection connection = dataSource.getConnection();
        try {
            connection.setAutoCommit(true);

            PreparedStatement statement = connection.prepareStatement("SELECT database_version "
                    + "FROM opf_registry_node " + "WHERE lookup = '" + packageLookup + "'");
            try {
                ResultSet resultSet = statement.executeQuery();
                try {
                    if (resultSet.next())
                        return new Version(resultSet.getInt(1));
                    else
                        throw new BusinessFunctionException("Can't find database version number.");
                } finally {
                    JdbcUtils.closeResultSet(resultSet);
                }
            } catch (SQLException e) {
                if (1054 == e.getErrorCode()) {
                    return new Version(1);
                }
                throw new RuntimeException(e);
            } finally {
                JdbcUtils.closeStatement(statement);
            }
        } finally {
            connection.setAutoCommit(false);
            JdbcUtils.closeConnection(connection);
        }
    } catch (SQLException e) {
        throw new RuntimeException(e);
    }
}