org.springframework.jdbc.core.PreparedStatementCallback Java Examples

The following examples show how to use org.springframework.jdbc.core.PreparedStatementCallback. 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: OracleMaterializedIncRecordExtractor.java    From yugong with GNU General Public License v2.0 6 votes vote down vote up
public Position ack(final List<Record> records) throws YuGongException {
    JdbcTemplate jdbcTemplate = new JdbcTemplate(context.getSourceDs());
    jdbcTemplate.execute(mlogCleanSql, new PreparedStatementCallback() {

        @Override
        public Object doInPreparedStatement(PreparedStatement ps) throws SQLException, DataAccessException {
            for (Record record : records) {
                OracleIncrementRecord incRecord = (OracleIncrementRecord) record;
                ps.setObject(1, incRecord.getRowId().getValue(), incRecord.getRowId().getColumn().getType());
                ps.addBatch();
            }

            ps.executeBatch();
            return null;
        }
    });

    return null;
}
 
Example #2
Source File: PreparedStatementCallbackImpl.java    From SimpleFlatMapper with MIT License 6 votes vote down vote up
public <H extends CheckedConsumer<T>> PreparedStatementCallback<H> newPreparedStatementCallback(final H handler) {
	return new PreparedStatementCallback<H>() {
		@Override
		public H doInPreparedStatement(
				PreparedStatement ps)
				throws SQLException, DataAccessException {
			ResultSet rs = ps.executeQuery();
			ResultSetExtractor<H> extractor = resultSetExtractor.newResultSetExtractor(handler);
			try {
				return extractor.extractData(rs);
			} finally {
				rs.close();
			}
		}
	};
}
 
Example #3
Source File: NamedParameterJdbcTemplateTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Test
public void testExecuteNoParameters() throws SQLException {
	given(preparedStatement.executeUpdate()).willReturn(1);

	Object result = namedParameterTemplate.execute(SELECT_NO_PARAMETERS,
			(PreparedStatementCallback<Object>) ps -> {
				assertEquals(preparedStatement, ps);
				ps.executeQuery();
				return "result";
			});

	assertEquals("result", result);
	verify(connection).prepareStatement(SELECT_NO_PARAMETERS);
	verify(preparedStatement).close();
	verify(connection).close();
}
 
Example #4
Source File: NamedParameterJdbcTemplateTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Test
public void testExecuteWithTypedParameters() throws SQLException {
	given(preparedStatement.executeUpdate()).willReturn(1);

	params.put("perfId", new SqlParameterValue(Types.DECIMAL, 1));
	params.put("priceId", new SqlParameterValue(Types.INTEGER, 1));
	Object result = namedParameterTemplate.execute(UPDATE_NAMED_PARAMETERS, params,
			(PreparedStatementCallback<Object>) ps -> {
				assertEquals(preparedStatement, ps);
				ps.executeUpdate();
				return "result";
			});

	assertEquals("result", result);
	verify(connection).prepareStatement(UPDATE_NAMED_PARAMETERS_PARSED);
	verify(preparedStatement).setObject(1, 1, Types.DECIMAL);
	verify(preparedStatement).setObject(2, 1, Types.INTEGER);
	verify(preparedStatement).close();
	verify(connection).close();
}
 
Example #5
Source File: NamedParameterJdbcTemplateTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Ignore("SPR-16340")
@Test
public void testExecuteArray() throws SQLException {
	given(preparedStatement.executeUpdate()).willReturn(1);

	List<Integer> typeIds = Arrays.asList(1, 2, 3);

	params.put("typeIds", typeIds);
	params.put("id", 1);
	Object result = namedParameterTemplate.execute(UPDATE_ARRAY_PARAMETERS, params,
			(PreparedStatementCallback<Object>) ps -> {
				assertEquals(preparedStatement, ps);
				ps.executeUpdate();
				return "result";
			});

	assertEquals("result", result);
	verify(connection).prepareStatement(UPDATE_ARRAY_PARAMETERS_PARSED);
	verify(preparedStatement).setObject(1, 1);
	verify(preparedStatement).setObject(2, 2);
	verify(preparedStatement).setObject(3, 3);
	verify(preparedStatement).setObject(4, 1);
	verify(preparedStatement).close();
	verify(connection).close();
}
 
Example #6
Source File: NamedParameterJdbcTemplateTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Test
public void testExecute() throws SQLException {
	given(preparedStatement.executeUpdate()).willReturn(1);

	params.put("perfId", 1);
	params.put("priceId", 1);
	Object result = namedParameterTemplate.execute(UPDATE_NAMED_PARAMETERS, params,
			(PreparedStatementCallback<Object>) ps -> {
				assertEquals(preparedStatement, ps);
				ps.executeUpdate();
				return "result";
			});

	assertEquals("result", result);
	verify(connection).prepareStatement(UPDATE_NAMED_PARAMETERS_PARSED);
	verify(preparedStatement).setObject(1, 1);
	verify(preparedStatement).setObject(2, 1);
	verify(preparedStatement).close();
	verify(connection).close();
}
 
Example #7
Source File: TableMetaGenerator.java    From yugong with GNU General Public License v2.0 6 votes vote down vote up
/**
 * <pre>
 * 常见的物化视图创建语句:
 * 1. CREATE MATERIALIZED VIEW LOG ON test_all_target with primary key;
 * 
 * 本方法,主要提取生成物化视图的表名
 * </pre>
 */
public static String getMLogTableName(final DataSource dataSource, final String schemaName, final String tableName) {
    JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);
    String sql = StringUtils.isNotEmpty(schemaName) ? mlogSchemaQuerySql : mlogQuerySql;
    return (String) jdbcTemplate.execute(sql, new PreparedStatementCallback() {

        public Object doInPreparedStatement(PreparedStatement ps) throws SQLException, DataAccessException {
            DatabaseMetaData metaData = ps.getConnection().getMetaData();
            String sName = getIdentifierName(schemaName, metaData);
            String tName = getIdentifierName(tableName, metaData);
            ps.setString(1, tName);
            if (StringUtils.isNotEmpty(schemaName)) {
                ps.setString(2, sName);
            }
            ResultSet rs = ps.executeQuery();
            String log = null;
            if (rs.next()) {
                log = rs.getString("log_table");
            }

            rs.close();
            return log;
        }
    });
}
 
Example #8
Source File: NamedParameterJdbcTemplateTests.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
@Test
public void testExecute() throws SQLException {
	given(preparedStatement.executeUpdate()).willReturn(1);

	params.put("perfId", 1);
	params.put("priceId", 1);
	Object result = namedParameterTemplate.execute(UPDATE_NAMED_PARAMETERS, params,
			new PreparedStatementCallback<Object>() {
				@Override
				public Object doInPreparedStatement(PreparedStatement ps)
						throws SQLException {
					assertEquals(preparedStatement, ps);
					ps.executeUpdate();
					return "result";
				}
			});

	assertEquals("result", result);
	verify(connection).prepareStatement(UPDATE_NAMED_PARAMETERS_PARSED);
	verify(preparedStatement).setObject(1, 1);
	verify(preparedStatement).setObject(2, 1);
	verify(preparedStatement).close();
	verify(connection).close();
}
 
Example #9
Source File: NamedParameterJdbcTemplateTests.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
@Test
public void testExecuteWithTypedParameters() throws SQLException {
	given(preparedStatement.executeUpdate()).willReturn(1);

	params.put("perfId", new SqlParameterValue(Types.DECIMAL, 1));
	params.put("priceId", new SqlParameterValue(Types.INTEGER, 1));
	Object result = namedParameterTemplate.execute(UPDATE_NAMED_PARAMETERS, params,
			new PreparedStatementCallback<Object>() {
				@Override
				public Object doInPreparedStatement(PreparedStatement ps)
						throws SQLException {
					assertEquals(preparedStatement, ps);
					ps.executeUpdate();
					return "result";
				}
			});

	assertEquals("result", result);
	verify(connection).prepareStatement(UPDATE_NAMED_PARAMETERS_PARSED);
	verify(preparedStatement).setObject(1, 1, Types.DECIMAL);
	verify(preparedStatement).setObject(2, 1, Types.INTEGER);
	verify(preparedStatement).close();
	verify(connection).close();
}
 
Example #10
Source File: NamedParameterJdbcTemplateTests.java    From effectivejava with Apache License 2.0 6 votes vote down vote up
@Test
public void testExecute() throws SQLException {
	given(preparedStatement.executeUpdate()).willReturn(1);

	params.put("perfId", 1);
	params.put("priceId", 1);
	Object result = namedParameterTemplate.execute(UPDATE_NAMED_PARAMETERS, params,
			new PreparedStatementCallback<Object>() {
				@Override
				public Object doInPreparedStatement(PreparedStatement ps)
						throws SQLException {
					assertEquals(preparedStatement, ps);
					ps.executeUpdate();
					return "result";
				}
			});

	assertEquals("result", result);
	verify(connection).prepareStatement(UPDATE_NAMED_PARAMETERS_PARSED);
	verify(preparedStatement).setObject(1, 1);
	verify(preparedStatement).setObject(2, 1);
	verify(preparedStatement).close();
	verify(connection).close();
}
 
Example #11
Source File: NamedParameterJdbcTemplateTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Test
public void testExecuteNoParameters() throws SQLException {
	given(preparedStatement.executeUpdate()).willReturn(1);

	Object result = namedParameterTemplate.execute(SELECT_NO_PARAMETERS,
			(PreparedStatementCallback<Object>) ps -> {
				assertEquals(preparedStatement, ps);
				ps.executeQuery();
				return "result";
			});

	assertEquals("result", result);
	verify(connection).prepareStatement(SELECT_NO_PARAMETERS);
	verify(preparedStatement).close();
	verify(connection).close();
}
 
Example #12
Source File: NamedParameterJdbcTemplateTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Test
public void testExecuteWithTypedParameters() throws SQLException {
	given(preparedStatement.executeUpdate()).willReturn(1);

	params.put("perfId", new SqlParameterValue(Types.DECIMAL, 1));
	params.put("priceId", new SqlParameterValue(Types.INTEGER, 1));
	Object result = namedParameterTemplate.execute(UPDATE_NAMED_PARAMETERS, params,
			(PreparedStatementCallback<Object>) ps -> {
				assertEquals(preparedStatement, ps);
				ps.executeUpdate();
				return "result";
			});

	assertEquals("result", result);
	verify(connection).prepareStatement(UPDATE_NAMED_PARAMETERS_PARSED);
	verify(preparedStatement).setObject(1, 1, Types.DECIMAL);
	verify(preparedStatement).setObject(2, 1, Types.INTEGER);
	verify(preparedStatement).close();
	verify(connection).close();
}
 
Example #13
Source File: NamedParameterJdbcTemplateTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Ignore("SPR-16340")
@Test
public void testExecuteArray() throws SQLException {
	given(preparedStatement.executeUpdate()).willReturn(1);

	List<Integer> typeIds = Arrays.asList(1, 2, 3);

	params.put("typeIds", typeIds);
	params.put("id", 1);
	Object result = namedParameterTemplate.execute(UPDATE_ARRAY_PARAMETERS, params,
			(PreparedStatementCallback<Object>) ps -> {
				assertEquals(preparedStatement, ps);
				ps.executeUpdate();
				return "result";
			});

	assertEquals("result", result);
	verify(connection).prepareStatement(UPDATE_ARRAY_PARAMETERS_PARSED);
	verify(preparedStatement).setObject(1, 1);
	verify(preparedStatement).setObject(2, 2);
	verify(preparedStatement).setObject(3, 3);
	verify(preparedStatement).setObject(4, 1);
	verify(preparedStatement).close();
	verify(connection).close();
}
 
Example #14
Source File: NamedParameterJdbcTemplateTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Test
public void testExecute() throws SQLException {
	given(preparedStatement.executeUpdate()).willReturn(1);

	params.put("perfId", 1);
	params.put("priceId", 1);
	Object result = namedParameterTemplate.execute(UPDATE_NAMED_PARAMETERS, params,
			(PreparedStatementCallback<Object>) ps -> {
				assertEquals(preparedStatement, ps);
				ps.executeUpdate();
				return "result";
			});

	assertEquals("result", result);
	verify(connection).prepareStatement(UPDATE_NAMED_PARAMETERS_PARSED);
	verify(preparedStatement).setObject(1, 1);
	verify(preparedStatement).setObject(2, 1);
	verify(preparedStatement).close();
	verify(connection).close();
}
 
Example #15
Source File: NamedParameterJdbcTemplateTests.java    From effectivejava with Apache License 2.0 6 votes vote down vote up
@Test
public void testExecuteWithTypedParameters() throws SQLException {
	given(preparedStatement.executeUpdate()).willReturn(1);

	params.put("perfId", new SqlParameterValue(Types.DECIMAL, 1));
	params.put("priceId", new SqlParameterValue(Types.INTEGER, 1));
	Object result = namedParameterTemplate.execute(UPDATE_NAMED_PARAMETERS, params,
			new PreparedStatementCallback<Object>() {
				@Override
				public Object doInPreparedStatement(PreparedStatement ps)
						throws SQLException {
					assertEquals(preparedStatement, ps);
					ps.executeUpdate();
					return "result";
				}
			});

	assertEquals("result", result);
	verify(connection).prepareStatement(UPDATE_NAMED_PARAMETERS_PARSED);
	verify(preparedStatement).setObject(1, 1, Types.DECIMAL);
	verify(preparedStatement).setObject(2, 1, Types.INTEGER);
	verify(preparedStatement).close();
	verify(connection).close();
}
 
Example #16
Source File: NamedParameterJdbcTemplateTests.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
@Test
public void testExecuteNoParameters() throws SQLException {
	given(preparedStatement.executeUpdate()).willReturn(1);

	Object result = namedParameterTemplate.execute(SELECT_NO_PARAMETERS,
			new PreparedStatementCallback<Object>() {
				@Override
				public Object doInPreparedStatement(PreparedStatement ps)
						throws SQLException {
					assertEquals(preparedStatement, ps);
					ps.executeQuery();
					return "result";
				}
			});

	assertEquals("result", result);
	verify(connection).prepareStatement(SELECT_NO_PARAMETERS);
	verify(preparedStatement).close();
	verify(connection).close();
}
 
Example #17
Source File: NamedParameterJdbcTemplateTests.java    From effectivejava with Apache License 2.0 6 votes vote down vote up
@Test
public void testExecuteNoParameters() throws SQLException {
	given(preparedStatement.executeUpdate()).willReturn(1);

	Object result = namedParameterTemplate.execute(SELECT_NO_PARAMETERS,
			new PreparedStatementCallback<Object>() {
				@Override
				public Object doInPreparedStatement(PreparedStatement ps)
						throws SQLException {
					assertEquals(preparedStatement, ps);
					ps.executeQuery();
					return "result";
				}
			});

	assertEquals("result", result);
	verify(connection).prepareStatement(SELECT_NO_PARAMETERS);
	verify(preparedStatement).close();
	verify(connection).close();
}
 
Example #18
Source File: NamedParameterJdbcTemplate.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Override
@Nullable
public <T> T execute(String sql, Map<String, ?> paramMap, PreparedStatementCallback<T> action)
		throws DataAccessException {

	return execute(sql, new MapSqlParameterSource(paramMap), action);
}
 
Example #19
Source File: NamedParameterJdbcTemplate.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Override
@Nullable
public <T> T execute(String sql, Map<String, ?> paramMap, PreparedStatementCallback<T> action)
		throws DataAccessException {

	return execute(sql, new MapSqlParameterSource(paramMap), action);
}
 
Example #20
Source File: RouteNodeDAOJpa.java    From rice with Educational Community License v2.0 5 votes vote down vote up
@Override
public List<String> getCurrentRouteNodeNames(final String documentId) {
    final DataSource dataSource = KEWServiceLocator.getDataSource();
    JdbcTemplate template = new JdbcTemplate(dataSource);
    List<String> names = template.execute(new PreparedStatementCreator() {
                public PreparedStatement createPreparedStatement(Connection connection) throws SQLException {
                    return connection.prepareStatement(CURRENT_ROUTE_NODE_NAMES_SQL);
                }
            }, new PreparedStatementCallback<List<String>>() {
                public List<String> doInPreparedStatement(
                        PreparedStatement statement) throws SQLException, DataAccessException {
                    List<String> routeNodeNames = new ArrayList<String>();
                    statement.setString(1, documentId);
                    ResultSet rs = statement.executeQuery();
                    try {
                        while (rs.next()) {
                            String name = rs.getString("nm");
                            routeNodeNames.add(name);
                        }
                    } finally {
                        if (rs != null) {
                            rs.close();
                        }
                    }
                    return routeNodeNames;
                }
            }
    );
    return names;
}
 
Example #21
Source File: NamedParameterJdbcTemplate.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Override
@Nullable
public <T> T execute(String sql, SqlParameterSource paramSource, PreparedStatementCallback<T> action)
		throws DataAccessException {

	return getJdbcOperations().execute(getPreparedStatementCreator(sql, paramSource), action);
}
 
Example #22
Source File: ExperimentDAOImpl.java    From gerbil with GNU Affero General Public License v3.0 5 votes vote down vote up
@Override
public void close() throws IOException {
    this.template.execute(SHUTDOWN, new PreparedStatementCallback<Object>() {
        @Override
        public Object doInPreparedStatement(PreparedStatement arg0) throws SQLException, DataAccessException {
            // nothing to do
            return null;
        }
    });
}
 
Example #23
Source File: XAOrderService.java    From shardingsphere with Apache License 2.0 5 votes vote down vote up
/**
 * Execute XA with exception.
 *
 * @param count insert record count
 */
@Transactional
@ShardingTransactionType(TransactionType.XA)
public void insertFailed(final int count) {
    jdbcTemplate.execute("INSERT INTO t_order (user_id, status) VALUES (?, ?)", (PreparedStatementCallback<TransactionType>) preparedStatement -> {
        doInsert(count, preparedStatement);
        throw new SQLException("mock transaction failed");
    });
}
 
Example #24
Source File: XAOrderService.java    From shardingsphere with Apache License 2.0 5 votes vote down vote up
/**
 * Execute XA.
 *
 * @param count insert record count
 * @return transaction type
 */
@Transactional
@ShardingTransactionType(TransactionType.XA)
public TransactionType insert(final int count) {
    return jdbcTemplate.execute("INSERT INTO t_order (user_id, status) VALUES (?, ?)", (PreparedStatementCallback<TransactionType>) preparedStatement -> {
        doInsert(count, preparedStatement);
        return TransactionTypeHolder.get();
    });
}
 
Example #25
Source File: SeataATOrderService.java    From shardingsphere with Apache License 2.0 5 votes vote down vote up
/**
 * Execute XA with exception.
 *
 * @param count insert record count
 */
@Transactional
@ShardingTransactionType(TransactionType.BASE)
public void insertFailed(final int count) {
    jdbcTemplate.execute("INSERT INTO t_order (user_id, status) VALUES (?, ?)", (PreparedStatementCallback<TransactionType>) preparedStatement -> {
        doInsert(count, preparedStatement);
        throw new SQLException("mock transaction failed");
    });
}
 
Example #26
Source File: SeataATOrderService.java    From shardingsphere with Apache License 2.0 5 votes vote down vote up
/**
 * Execute XA.
 *
 * @param count insert record count
 * @return transaction type
 */
@Transactional
@ShardingTransactionType(TransactionType.BASE)
public TransactionType insert(final int count) {
    return jdbcTemplate.execute("INSERT INTO t_order (user_id, status) VALUES (?, ?)", (PreparedStatementCallback<TransactionType>) preparedStatement -> {
        doInsert(count, preparedStatement);
        return TransactionTypeHolder.get();
    });
}
 
Example #27
Source File: XAOrderService.java    From shardingsphere with Apache License 2.0 5 votes vote down vote up
/**
 * Execute XA with exception.
 *
 * @param count insert record count
 */
@Transactional
@ShardingTransactionType(TransactionType.XA)
public void insertFailed(final int count) {
    jdbcTemplate.execute("INSERT INTO t_order (user_id, status) VALUES (?, ?)", (PreparedStatementCallback<TransactionType>) preparedStatement -> {
        doInsert(count, preparedStatement);
        throw new SQLException("mock transaction failed");
    });
}
 
Example #28
Source File: XAOrderService.java    From shardingsphere with Apache License 2.0 5 votes vote down vote up
/**
 * Execute XA.
 *
 * @param count insert record count
 * @return transaction type
 */
@Transactional
@ShardingTransactionType(TransactionType.XA)
public TransactionType insert(final int count) {
    return jdbcTemplate.execute("INSERT INTO t_order (user_id, status) VALUES (?, ?)", (PreparedStatementCallback<TransactionType>) preparedStatement -> {
        doInsert(count, preparedStatement);
        return TransactionTypeHolder.get();
    });
}
 
Example #29
Source File: TableMetaGenerator.java    From yugong with GNU General Public License v2.0 5 votes vote down vote up
/**
 * 获取DRDS下表的拆分字段, 返回格式为 id,name
 */
public static String getShardKeyByDRDS(final DataSource dataSource, final String schemaName, final String tableName) {
    JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);
    try {
        return (String) jdbcTemplate.execute(queryShardKey, new PreparedStatementCallback() {

            public Object doInPreparedStatement(PreparedStatement ps) throws SQLException, DataAccessException {
                DatabaseMetaData metaData = ps.getConnection().getMetaData();
                // String sName = getIdentifierName(schemaName, metaData);
                String tName = getIdentifierName(tableName, metaData);

                ps.setString(1, tName);
                ResultSet rs = ps.executeQuery();
                String log = null;
                if (rs.next()) {
                    log = rs.getString("KEYS");
                }

                rs.close();
                return log;
            }
        });
    } catch (DataAccessException e) {
        // 兼容下oracle源库和目标库DRDS表名不一致的情况,识别一下表名不存在
        Throwable cause = e.getRootCause();
        if (cause instanceof SQLException) {
            // ER_NO_SUCH_TABLE
            if (((SQLException) cause).getErrorCode() == 1146) {
                return null;
            }
        }

        throw e;
    }
}
 
Example #30
Source File: ContinueExtractor.java    From yugong with GNU General Public License v2.0 5 votes vote down vote up
private Object getMinId() {
    if (jdbcTemplate == null || !StringUtils.isNotBlank(oracleFullRecordExtractor.getGetMinPkSql())) {
        throw new YuGongException("jdbcTemplate or getMinPkSql is null while getMinId");
    }
    Object min = jdbcTemplate.execute(oracleFullRecordExtractor.getGetMinPkSql(),
        (PreparedStatementCallback) ps -> {
            ResultSet rs = ps.executeQuery();
            Object re = null;
            while (rs.next()) {
                re = rs.getObject(1);
                break;
            }
            return re;
        });

    if (min != null) {
        if (min instanceof Number) {
            min = Long.valueOf(String.valueOf(min)) - 1;
        } else {
            min = "";
        }
    } else {
        if (min instanceof Number) {
            min = 0;
        } else {
            min = "";
        }
    }

    return min;
}