Java Code Examples for org.springframework.jdbc.core.PreparedStatementCallback

The following examples show how to use org.springframework.jdbc.core.PreparedStatementCallback. These examples are extracted from open source projects. 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
@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 2
@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 3
@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 4
@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 5
@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 6
@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 7
@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 8
@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 9
@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 10
@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 11
@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 12
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 13
Source Project: yugong   Source File: TableMetaGenerator.java    License: 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 14
Source Project: SimpleFlatMapper   Source File: PreparedStatementCallbackImpl.java    License: 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 15
@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 16
@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 17
@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 Project: spring-analysis-note   Source File: NamedParameterJdbcTemplate.java    License: 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 19
Source Project: spring-analysis-note   Source File: NamedParameterJdbcTemplate.java    License: 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 Project: java-technology-stack   Source File: NamedParameterJdbcTemplate.java    License: 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 21
Source Project: java-technology-stack   Source File: NamedParameterJdbcTemplate.java    License: 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 22
Source Project: yugong   Source File: ContinueExtractor.java    License: 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;
}
 
Example 23
Source Project: yugong   Source File: TableMetaGenerator.java    License: 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 24
Source Project: shardingsphere   Source File: XAOrderService.java    License: 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 Project: shardingsphere   Source File: XAOrderService.java    License: 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 26
Source Project: shardingsphere   Source File: SeataATOrderService.java    License: 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 Project: shardingsphere   Source File: SeataATOrderService.java    License: 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 28
Source Project: shardingsphere   Source File: XAOrderService.java    License: 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 Project: shardingsphere   Source File: XAOrderService.java    License: 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 30
@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;
        }
    });
}