org.springframework.jdbc.core.StatementCallback Java Examples

The following examples show how to use org.springframework.jdbc.core.StatementCallback. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: RdbEventRecordLoader.java    From DataLink with Apache License 2.0 6 votes vote down vote up
private boolean executeSql(DbDialect dbDialect, String sql) {
    TransactionTemplate transactionTemplate = dbDialect.getTransactionTemplate();
    int originalBehavior = transactionTemplate.getPropagationBehavior();

    try {
        transactionTemplate.setPropagationBehavior(TransactionDefinition.PROPAGATION_NOT_SUPPORTED);
        return transactionTemplate.execute(transactionStatus -> {
            try {
                dbDialect.getJdbcTemplate().execute(new StatementCallback<Boolean>() {

                    public Boolean doInStatement(Statement stmt) throws SQLException, DataAccessException {
                        return stmt.execute(sql);
                    }
                });
                logger.info("Sql for adding-column is executed successfully : sql is {}", sql);
                return true;
            } catch (Throwable t) {
                logger.error(String.format("skip exception for adding-column-sql : sql is %s", sql), t);
            }
            return false;
        });
    } finally {
        transactionTemplate.setPropagationBehavior(originalBehavior);
    }
}
 
Example #2
Source File: CobarAdapter.java    From tddl5 with Apache License 2.0 6 votes vote down vote up
@Override
public Pair<Long, Long> getCurrentTimeMillis() {
    return (Pair<Long, Long>) getJdbcTemplate().execute(new StatementCallback() {

        @Override
        public Object doInStatement(Statement stmt) throws SQLException, DataAccessException {
            ResultSet rs = null;
            try {
                long time1 = System.currentTimeMillis();
                rs = stmt.executeQuery("show @@status.time");
                long time2 = System.currentTimeMillis();
                if (rs.next()) {
                    return new Pair<Long, Long>(time1 + (time2 - time1) / 2, rs.getLong(1));
                } else {
                    throw new IncorrectResultSizeDataAccessException(1, 0);
                }
            } finally {
                if (rs != null) {
                    rs.close();
                }
            }
        }
    });
}
 
Example #3
Source File: DdlEventInterceptor.java    From DataLink with Apache License 2.0 5 votes vote down vote up
private void executeSql(MediaMappingInfo mappingInfo, DbDialect dbDialect, String sql) {
    try {
        Boolean result = dbDialect.getJdbcTemplate().execute(new StatementCallback<Boolean>() {

            public Boolean doInStatement(Statement stmt) throws SQLException, DataAccessException {
                return stmt.execute(sql);
            }
        });
        logger.info("ddl is executed successfully: media-mapping-id is {}, sql is {}", mappingInfo.getId(), sql);
    } catch (Throwable t) {
        logger.error(String.format("skip exception for ddl: media-mapping-id is %s, sql is %s", mappingInfo.getId(), sql), t);
    }
}
 
Example #4
Source File: MetricCacher.java    From graphouse with Apache License 2.0 5 votes vote down vote up
private void saveMetrics() {
    clickHouseJdbcTemplate.execute(
        (StatementCallback<Void>) stmt -> {
            ClickHouseStatementImpl statement = (ClickHouseStatementImpl) stmt;
            MetricsStreamCallback metricsStreamCallback = new MetricsStreamCallback(
                metrics, statement.getConnection().getTimeZone()
            );
            statement.sendRowBinaryStream(
                "INSERT INTO " + graphiteDataWriteTable + " (metric, value, timestamp, date, updated)",
                metricsStreamCallback
            );
            return null;
        }
    );
}
 
Example #5
Source File: DbAdminManagerSupport.java    From jdal with Apache License 2.0 5 votes vote down vote up
public boolean execute(final String sql) throws DataAccessException {
	if (log.isDebugEnabled()) {
		log.debug("Executing SQL statement [" + sql + "]");
	}
	class ExecuteStatementCallback implements StatementCallback<Boolean>, SqlProvider {
		public Boolean doInStatement(Statement stmt) throws SQLException {
			return stmt.execute(sql);
		}
		public String getSql() {
			return sql;
		}
	}
	
	return  template.execute(new ExecuteStatementCallback());
}
 
Example #6
Source File: BatchJdbcTemplate.java    From buffer-slayer with Apache License 2.0 4 votes vote down vote up
public <T> T execute(StatementCallback<T> action) throws DataAccessException {
  return delegate.execute(action);
}
 
Example #7
Source File: KratosJdbcTemplate.java    From kratos-1 with Apache License 2.0 4 votes vote down vote up
@Override
public <T> T execute(StatementCallback<T> action) throws DataAccessException {

	return super.execute(action);
}
 
Example #8
Source File: TestUtilities.java    From rice with Educational Community License v2.0 4 votes vote down vote up
public static void clearTables(final PlatformTransactionManager transactionManager, final DataSource dataSource, final String edenSchemaName, final List<String> dontClear) {
    LOG.info("Clearing tables for schema " + edenSchemaName);
    if (dataSource == null) {
        Assert.fail("Null data source given");
    }
    if (edenSchemaName == null || edenSchemaName.equals("")) {
        Assert.fail("Empty eden schema name given");
    }
    new TransactionTemplate(transactionManager).execute(new TransactionCallback() {
        public Object doInTransaction(TransactionStatus status) {
            verifyTestEnvironment(dataSource);
            JdbcTemplate template = new JdbcTemplate(dataSource);
            return template.execute(new StatementCallback() {
                public Object doInStatement(Statement statement) throws SQLException {
                    List<String> reEnableConstraints = new ArrayList<String>();
                	ResultSet resultSet = statement.getConnection().getMetaData().getTables(null, edenSchemaName, null, new String[] { "TABLE" });
                    while (resultSet.next()) {
                        String tableName = resultSet.getString("TABLE_NAME");
                        if (tableName.startsWith("EN_") && !dontClear.contains(tableName)) {
                        	ResultSet keyResultSet = statement.getConnection().getMetaData().getExportedKeys(null, edenSchemaName, tableName);
                        	while (keyResultSet.next()) {
                        		String fkName = keyResultSet.getString("FK_NAME");
                        		String fkTableName = keyResultSet.getString("FKTABLE_NAME");
                        		statement.addBatch("ALTER TABLE "+fkTableName+" DISABLE CONSTRAINT "+fkName);
                        		reEnableConstraints.add("ALTER TABLE "+fkTableName+" ENABLE CONSTRAINT "+fkName);
                        	}
                        	keyResultSet.close();
                        	statement.addBatch("DELETE FROM "+tableName);
                        }
                    }
                    for (String constraint : reEnableConstraints) {
                		statement.addBatch(constraint);
                	}
                    statement.executeBatch();
                    resultSet.close();
                    return null;
                }
            });
        }
    });
    LOG.info("Tables successfully cleared for schema " + edenSchemaName);
}
 
Example #9
Source File: ActionListTest.java    From rice with Educational Community License v2.0 4 votes vote down vote up
@Test public void testActionListCount() throws Exception {
	setUpOldSchool();
    TransactionTemplate transactionTemplate = getTransactionTemplate();
    transactionTemplate.execute(new TransactionCallback() {
        @Override
        public Object doInTransaction(TransactionStatus status) {
        	return TestUtilities.getJdbcTemplate().execute(new StatementCallback() {
        		@Override
                public Object doInStatement(Statement stmt) {
                    try {
                        Connection conn = stmt.getConnection();
                        PreparedStatement ps = conn.prepareStatement("select distinct PRNCPL_ID from krew_actn_itm_t");
                        ResultSet rs = ps.executeQuery();
                        int emplIdCnt = 0;
                        int loopCnt = 0;
                        //do first 5 for time sake
                        while (rs.next() && ++loopCnt < 6) {
                            String workflowId = rs.getString(1);
                            PreparedStatement ps1 = conn.prepareStatement("select count(*) from krew_actn_itm_t where PRNCPL_ID = ?");
                            ps1.setString(1, workflowId);
                            ResultSet rsWorkflowIdCnt = ps1.executeQuery();
                            if (rsWorkflowIdCnt.next()) {
                                emplIdCnt = rsWorkflowIdCnt.getInt(1);
                            } else {
                                throw new Exception("WorkflowId " + workflowId + " didn't return a count.  Test SQL invalid.");
                            }
                            Collection<ActionItem> actionList = getActionListService().findByPrincipalId(workflowId);
                            assertEquals("ActionItemService returned incorrect number of ActionItems for user " + workflowId + " ActionList", emplIdCnt, actionList.size());
                            ps1.close();
                            rsWorkflowIdCnt.close();
                        }
                        rs.close();
                        ps.close();
                    } catch (Exception e) {
                        throw new RuntimeException(e);
                    }
                    return null;
                }
            });
        }
    });
}
 
Example #10
Source File: ActionListTest.java    From rice with Educational Community License v2.0 4 votes vote down vote up
@Test
public void testActionListMaxActionItemDateAssignedAndCountForUser() throws Exception {
    // sanity check first - just attempt to call the method
    getActionListService().getMaxActionItemDateAssignedAndCountForUser("123456");
    setUpOldSchool();
    TransactionTemplate transactionTemplate = getTransactionTemplate();
    transactionTemplate.execute(new TransactionCallback() {
        @Override
        public Object doInTransaction(TransactionStatus status) {
            return TestUtilities.getJdbcTemplate().execute(new StatementCallback() {
                @Override
                public Object doInStatement(Statement stmt) {
                    try {
                        Connection conn = stmt.getConnection();
                        PreparedStatement ps = conn.prepareStatement(
                                "select distinct PRNCPL_ID from krew_actn_itm_t");
                        ResultSet rs = ps.executeQuery();
                        long cnt = 0;
                        Date maxDate = null;
                        int loopCnt = 0;
                        //do first 5 for time sake
                        while (rs.next() && ++loopCnt < 6) {
                            String workflowId = rs.getString(1);
                            PreparedStatement ps1 = conn.prepareStatement(
                                    "select max(ASND_DT) as max_date, count(distinct(doc_hdr_id)) as total_records"
                                            + "  from ("
                                            + "  select ASND_DT,doc_hdr_id "
                                            + "  from KREW_ACTN_ITM_T   where    prncpl_id=? "
                                            + "  group by  ASND_DT,doc_hdr_id "
                                            + "  ) T");
                            ps1.setString(1, workflowId);
                            ResultSet rsWorkflowIdCnt = ps1.executeQuery();
                            if (rsWorkflowIdCnt.next()) {
                                maxDate = rsWorkflowIdCnt.getTimestamp(1);
                                cnt = rsWorkflowIdCnt.getLong(2);
                            } else {
                                throw new Exception(
                                        "WorkflowId " + workflowId + " didn't return a result set.  Test SQL invalid.");
                            }
                            List<Object> ls = getActionListService().getMaxActionItemDateAssignedAndCountForUser(workflowId);
                            assertEquals((Long) cnt, ls.get(1));
                            assertEquals(maxDate, ls.get(0));
                            ps1.close();
                            rsWorkflowIdCnt.close();
                        }
                        if ( loopCnt == 0 ) {
                            Assert.fail( "ERROR - NO PRINCIPAL IDs RETURNED FROM ACTION ITEM SEARCH - TEST DID NOT RUN" );
                        }
                        rs.close();
                        ps.close();
                    } catch (Exception e) {
                        throw new RuntimeException(e);
                    }
                    return null;
                }
            });
        }
    });
}
 
Example #11
Source File: ClearDatabaseLifecycle.java    From rice with Educational Community License v2.0 4 votes vote down vote up
protected void clearTables(final PlatformTransactionManager transactionManager, final DataSource dataSource) {
    Assert.assertNotNull("DataSource could not be located.", dataSource);
    try {
        StopWatch s = new StopWatch();
        s.start();
        new TransactionTemplate(transactionManager).execute(new TransactionCallback() {
            public Object doInTransaction(final TransactionStatus status) {
                verifyTestEnvironment(dataSource);
                return new JdbcTemplate(dataSource).execute(new StatementCallback() {
                    public Object doInStatement(Statement statement) throws SQLException {
                        String schemaName = statement.getConnection().getMetaData().getUserName().toUpperCase();
                        LOG.info("Clearing tables for schema " + schemaName);
                        if (StringUtils.isBlank(schemaName)) {
                            Assert.fail("Empty schema name given");
                        }
                        final List<String> reEnableConstraints = new ArrayList<String>();
                        DatabaseMetaData metaData = statement.getConnection().getMetaData();
                        Map<String, List<String[]>> exportedKeys = indexExportedKeys(metaData, schemaName);
                        final ResultSet resultSet = metaData.getTables(null, schemaName, null, new String[] { "TABLE" });
                        final StringBuilder logStatements = new StringBuilder();
                        while (resultSet.next()) {
                            String tableName = resultSet.getString("TABLE_NAME");
                            if (shouldTableBeCleared(tableName)) {
                                if (!isUsingDerby(metaData) && isUsingOracle(metaData)) {
                                	List<String[]> exportedKeyNames = exportedKeys.get(tableName);
                                	if (exportedKeyNames != null) {
                                		for (String[] exportedKeyName : exportedKeyNames) {
                                			final String fkName = exportedKeyName[0];
                                			final String fkTableName = exportedKeyName[1];
                                			final String disableConstraint = "ALTER TABLE " + fkTableName + " DISABLE CONSTRAINT " + fkName;
                                			logStatements.append("Disabling constraints using statement ->" + disableConstraint + "<-\n");
                                			statement.addBatch(disableConstraint);
                                			reEnableConstraints.add("ALTER TABLE " + fkTableName + " ENABLE CONSTRAINT " + fkName);
                                		}
                                	}
                                } else if (isUsingMySQL(metaData)) {
                                	statement.addBatch("SET FOREIGN_KEY_CHECKS = 0");
                                }
                                String deleteStatement = "DELETE FROM " + tableName;
                                logStatements.append("Clearing contents using statement ->" + deleteStatement + "<-\n");
                                statement.addBatch(deleteStatement);
                            }
                        }
                        for (final String constraint : reEnableConstraints) {
                            logStatements.append("Enabling constraints using statement ->" + constraint + "<-\n");
                            statement.addBatch(constraint);
                        }
                        if (isUsingMySQL(metaData)) {
                        	statement.addBatch("SET FOREIGN_KEY_CHECKS = 1");
                        }
                        LOG.info(logStatements);
                        
                        int[] results = statement.executeBatch();
                        for (int index = 0; index < results.length; index++) {
                        	if (results[index] == Statement.EXECUTE_FAILED) {
                				Assert.fail("Execution of database clear statement failed.");
                        	}
                        	
                        }
                        resultSet.close();
                        LOG.info("Tables successfully cleared for schema " + schemaName);
                        return null;
                    }
                });
            }
        });
        s.stop();
        LOG.info("Time to clear tables: " + DurationFormatUtils.formatDurationHMS(s.getTime()));
    } catch (Exception e) {
        LOG.error(e);
        throw new RuntimeException(e);
    }
}