如何使用 Spring 的 JDBCTemplate 有效地执行 IN() SQL 查询? [英] How to execute IN() SQL queries with Spring's JDBCTemplate effectively?
本文介绍了如何使用 Spring 的 JDBCTemplate 有效地执行 IN() SQL 查询?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想知道是否有更优雅的方式来使用 Spring 的 JDBCTemplate 进行 IN() 查询.目前我做这样的事情:
I was wondering if there is a more elegant way to do IN() queries with Spring's JDBCTemplate. Currently I do something like that:
StringBuilder jobTypeInClauseBuilder = new StringBuilder();
for(int i = 0; i < jobTypes.length; i++) {
Type jobType = jobTypes[i];
if(i != 0) {
jobTypeInClauseBuilder.append(',');
}
jobTypeInClauseBuilder.append(jobType.convert());
}
这是非常痛苦的,因为如果我有九行只是为了构建 IN() 查询的子句.我想要一些类似准备好的语句的参数替换
Which is quite painful since if I have nine lines just for building the clause for the IN() query. I would like to have something like the parameter substitution of prepared statements
推荐答案
你想要一个参数来源:
Set<Integer> ids = ...;
MapSqlParameterSource parameters = new MapSqlParameterSource();
parameters.addValue("ids", ids);
List<Foo> foo = getJdbcTemplate().query("SELECT * FROM foo WHERE a IN (:ids)",
parameters, getRowMapper());
这仅在 getJdbcTemplate()
返回类型为 NamedParameterJdbcTemplate
This only works if getJdbcTemplate()
returns an instance of type NamedParameterJdbcTemplate
这篇关于如何使用 Spring 的 JDBCTemplate 有效地执行 IN() SQL 查询?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文