如何有效地使用Spring的JDBCTemplate执行IN()SQL查询? [英] How to execute IN() SQL queries with Spring's JDBCTemplate effectivly?

查看:105
本文介绍了如何有效地使用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());
}

这是非常痛苦的,因为如果我有9行仅用于构建子句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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆