Example usage for org.springframework.jdbc.datasource DataSourceTransactionManager commit

List of usage examples for org.springframework.jdbc.datasource DataSourceTransactionManager commit

Introduction

In this page you can find the example usage for org.springframework.jdbc.datasource DataSourceTransactionManager commit.

Prototype

@Override
public final void commit(TransactionStatus status) throws TransactionException 

Source Link

Document

This implementation of commit handles participating in existing transactions and programmatic rollback requests.

Usage

From source file:cn.uncode.dal.internal.shards.transaction.MultiDataSourcesTransactionManager.java

@Override
public void commit(TransactionStatus status) throws TransactionException {

    Throwable ex = null;// www. j ava  2s .co  m
    //      Collections.reverse(dataSources);
    for (int i = dataSources.size() - 1; i >= 0; i--) {
        DataSource dataSource = dataSources.get(i);
        try {
            commitCount.addAndGet(1);

            log.debug("Committing JDBC transaction");

            DataSourceTransactionManager txManager = this.transactionManagers.get(dataSource);

            TransactionStatus transactionStatus = ((MultiDataSourcesTransactionStatus) status).get(dataSource);
            txManager.commit(transactionStatus);

            log.debug("Commit JDBC transaction success");
        } catch (Throwable e) {
            log.debug("Could not commit JDBC transaction", e);
            ex = e;
        } finally {
            commitCount.addAndGet(-1);
        }
    }

    if (ex != null) {
        throw new RuntimeException(ex);
    }

}

From source file:org.tec.webapp.jdbc.entity.TestUserRole.java

/**
 * create seed user/*from   w  w w.  j  av a2s. c  om*/
 * @return the seed user
 */
protected UserRoleBean testUserRole() {
    DataSourceTransactionManager tmgr = (DataSourceTransactionManager) mAppContext
            .getBean("transactionManager");

    TransactionStatus tranStat = tmgr.getTransaction(new DefaultTransactionDefinition());

    try {
        UserBean user = new User();

        user.setUserName("junit");
        user.setEmail("junit@test.null");

        Long userId = mUserDba.insert(user);
        Assert.assertTrue("id is foobared", userId > 0);

        user.setUserId(userId.intValue());

        UserRoleBean roleBean = new UserRole();

        roleBean.setUser(user);

        roleBean.setRole(RoleType.ROLE_GUEST);

        Long id = mUserRoleDba.insert(roleBean);

        roleBean.setUserRoleId(id.intValue());

        List<UserRoleBean> l = mUserRoleDba.getRoles(new Long(user.getUserId()));

        Assert.assertTrue("should be at least 1 role", l.size() > 0);

        tmgr.commit(tranStat);

        return roleBean;
    } catch (Throwable t) {
        tmgr.rollback(tranStat);
        throw new RuntimeException("failed to create user role", t);
    }
}

From source file:com.foilen.smalltools.upgrader.tasks.AbstractFlywayMigrateOffUpgradeTask.java

@Override
public void execute() {
    DataSourceTransactionManager transactionManager = new DataSourceTransactionManager(
            jdbcTemplate.getDataSource());

    // Check if the schema_version table exists
    List<String> tableNames = mysqlTablesFindAll();
    List<String> executed;
    if (tableNames.contains("schema_version")) {
        executed = jdbcTemplate.queryForList("SELECT script FROM schema_version WHERE success = 1",
                String.class);
        jdbcTemplate.update("DELETE FROM schema_version WHERE success = 0");
    } else {/*from ww  w  .  j  a  v  a2  s .  c o  m*/
        executed = new ArrayList<>();
        logger.info("Flyway table does not exists. Creating it");
        updateFromResource("flyway-schema_version.sql", AbstractFlywayMigrateOffUpgradeTask.class);
    }

    PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
    AntPathMatcher pathMatcher = new AntPathMatcher();
    resolver.setPathMatcher(pathMatcher);
    Resource[] resources;
    try {
        resources = resolver.getResources("classpath:db/migration/*.sql");
    } catch (IOException e) {
        throw new SmallToolsException("Problem getting the sql files", e);
    }

    int rank = executed.size() + 1;
    List<String> scriptNames = Arrays.asList(resources).stream() //
            .map(Resource::getFilename) //
            .sorted() //
            .collect(Collectors.toList());
    for (String scriptName : scriptNames) {
        boolean needRetry = true;
        if (executed.contains(scriptName)) {
            logger.info("[{}] Already executed. Skip", scriptName);
        } else {
            logger.info("[{}] To execute", scriptName);
            for (int retryCount = 0; needRetry; ++retryCount) {
                needRetry = false;
                TransactionStatus transactionStatus = transactionManager
                        .getTransaction(new DefaultTransactionDefinition());
                try {
                    // Do the update
                    updateFromResource("/db/migration/" + scriptName);

                    // Save in schema_version
                    jdbcTemplate.update("INSERT INTO schema_version " //
                            + "(version_rank, installed_rank, version, description, type, script, installed_by, execution_time, success) " //
                            + "VALUES (?,?,?,'','SQL',?,'upgrader',1, 1)", //
                            rank, rank, //
                            scriptName.substring(0, Math.min(50, scriptName.length())), //
                            scriptName //
                    );
                    ++rank;
                    transactionManager.commit(transactionStatus);
                } catch (Exception e) {
                    logger.warn("[{}] Problem executing script. Will purge the connections and retry",
                            scriptName);
                    transactionManager.rollback(transactionStatus);
                    needRetry = true;
                    purgeConnections();
                    if (retryCount > 5) {
                        throw new SmallToolsException("Problem executing script: " + scriptName, e);
                    }
                }

            }
        }
    }

    if (deleteSchemaTable) {
        logger.info("Deleting the Flyway schema_version table");
        jdbcTemplate.update("DROP TABLE schema_version");
    }

}

From source file:org.ohmage.query.impl.SurveyUploadQuery.java

@Override
public List<Integer> insertSurveys(final String username, final String client, final String campaignUrn,
        final List<SurveyResponse> surveyUploadList, final Map<UUID, Image> bufferedImageMap,
        final Map<String, Video> videoContentsMap, final Map<String, Audio> audioContentsMap)
        throws DataAccessException {

    List<Integer> duplicateIndexList = new ArrayList<Integer>();
    int numberOfSurveys = surveyUploadList.size();

    // The following variables are used in logging messages when errors occur
    SurveyResponse currentSurveyResponse = null;
    PromptResponse currentPromptResponse = null;
    String currentSql = null;/*from  w  ww.  ja v a  2 s.c o m*/

    List<File> fileList = new LinkedList<File>();

    // Wrap all of the inserts in a transaction 
    DefaultTransactionDefinition def = new DefaultTransactionDefinition();
    def.setName("survey upload");
    DataSourceTransactionManager transactionManager = new DataSourceTransactionManager(getDataSource());
    TransactionStatus status = transactionManager.getTransaction(def); // begin transaction

    // Use a savepoint to handle nested rollbacks if duplicates are found
    Object savepoint = status.createSavepoint();

    try { // handle TransactionExceptions

        for (int surveyIndex = 0; surveyIndex < numberOfSurveys; surveyIndex++) {

            try { // handle DataAccessExceptions

                final SurveyResponse surveyUpload = surveyUploadList.get(surveyIndex);
                currentSurveyResponse = surveyUpload;
                currentSql = SQL_INSERT_SURVEY_RESPONSE;

                KeyHolder idKeyHolder = new GeneratedKeyHolder();

                // First, insert the survey
                getJdbcTemplate().update(new PreparedStatementCreator() {
                    public PreparedStatement createPreparedStatement(Connection connection)
                            throws SQLException {
                        PreparedStatement ps = connection.prepareStatement(SQL_INSERT_SURVEY_RESPONSE,
                                Statement.RETURN_GENERATED_KEYS);

                        String locationString = null;
                        Location location = surveyUpload.getLocation();
                        if (location != null) {
                            try {
                                locationString = location.toJson(false, LocationColumnKey.ALL_COLUMNS)
                                        .toString();
                            } catch (JSONException e) {
                                throw new SQLException(e);
                            } catch (DomainException e) {
                                throw new SQLException(e);
                            }
                        }

                        ps.setString(1, surveyUpload.getSurveyResponseId().toString());
                        ps.setString(2, username);
                        ps.setString(3, campaignUrn);
                        ps.setLong(4, surveyUpload.getTime());
                        ps.setString(5, surveyUpload.getTimezone().getID());
                        ps.setString(6, surveyUpload.getLocationStatus().toString());
                        ps.setString(7, locationString);
                        ps.setString(8, surveyUpload.getSurvey().getId());
                        try {
                            ps.setString(9,
                                    surveyUpload
                                            .toJson(false, false, false, false, true, true, true, true, true,
                                                    false, false, true, true, true, true, false, false)
                                            .toString());
                        } catch (JSONException e) {
                            throw new SQLException("Couldn't create the JSON.", e);
                        } catch (DomainException e) {
                            throw new SQLException("Couldn't create the JSON.", e);
                        }
                        ps.setString(10, client);
                        ps.setTimestamp(11, new Timestamp(System.currentTimeMillis()));
                        try {
                            ps.setString(12, surveyUpload.getLaunchContext().toJson(true).toString());
                        } catch (JSONException e) {
                            throw new SQLException("Couldn't create the JSON.", e);
                        }
                        try {
                            ps.setString(13, PreferenceCache.instance()
                                    .lookup(PreferenceCache.KEY_DEFAULT_SURVEY_RESPONSE_SHARING_STATE));
                        } catch (CacheMissException e) {
                            throw new SQLException("Error reading from the cache.", e);
                        }
                        return ps;
                    }
                }, idKeyHolder);

                savepoint = status.createSavepoint();

                final Number surveyResponseId = idKeyHolder.getKey(); // the primary key on the survey_response table for the 
                                                                      // just-inserted survey
                currentSql = SQL_INSERT_PROMPT_RESPONSE;

                // Now insert each prompt response from the survey
                Collection<Response> promptUploadList = surveyUpload.getResponses().values();

                createPromptResponse(username, client, surveyResponseId, fileList, promptUploadList, null,
                        bufferedImageMap, videoContentsMap, audioContentsMap, transactionManager, status);

            } catch (DataIntegrityViolationException dive) { // a unique index exists only on the survey_response table

                if (isDuplicate(dive)) {

                    LOGGER.debug("Found a duplicate survey upload message for user " + username);

                    duplicateIndexList.add(surveyIndex);
                    status.rollbackToSavepoint(savepoint);

                } else {

                    // Some other integrity violation occurred - bad!! All 
                    // of the data to be inserted must be validated before 
                    // this query runs so there is either missing validation 
                    // or somehow an auto_incremented key has been duplicated.

                    LOGGER.error("Caught DataAccessException", dive);
                    logErrorDetails(currentSurveyResponse, currentPromptResponse, currentSql, username,
                            campaignUrn);
                    for (File f : fileList) {
                        f.delete();
                    }
                    rollback(transactionManager, status);
                    throw new DataAccessException(dive);
                }

            } catch (org.springframework.dao.DataAccessException dae) {

                // Some other database problem happened that prevented
                // the SQL from completing normally.

                LOGGER.error("caught DataAccessException", dae);
                logErrorDetails(currentSurveyResponse, currentPromptResponse, currentSql, username,
                        campaignUrn);
                for (File f : fileList) {
                    f.delete();
                }
                rollback(transactionManager, status);
                throw new DataAccessException(dae);
            }

        }

        // Finally, commit the transaction
        transactionManager.commit(status);
        LOGGER.info("Completed survey message persistence");
    }

    catch (TransactionException te) {

        LOGGER.error("failed to commit survey upload transaction, attempting to rollback", te);
        rollback(transactionManager, status);
        for (File f : fileList) {
            f.delete();
        }
        logErrorDetails(currentSurveyResponse, currentPromptResponse, currentSql, username, campaignUrn);
        throw new DataAccessException(te);
    }

    LOGGER.info(
            "Finished inserting survey responses and any associated images into the database and the filesystem.");
    return duplicateIndexList;
}