193

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());
}

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

0

5 Answers 5

297

You want a parameter source:

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());

This only works if getJdbcTemplate() returns an instance of type NamedParameterJdbcTemplate

9
  • 8
    Perfect, the NamedParameterJdbcTemplate was exactly what i was looking for. Additionally i like named parameters more than those question marks all over the place. Thanks a lot!
    – Malax
    Aug 25, 2009 at 10:43
  • 8
    This works for small lists, but attempting to use it on a large list results in a query where :ids is replaced with "?,?,?,?,?......" and with enough list items it overflows. Is there a solution that works for large lists?
    – nsayer
    Apr 26, 2010 at 17:45
  • You should probably insert the values into a temporary table and build the condition using WHERE NOT EXISTS (SELECT ...).
    – yawn
    May 26, 2010 at 11:17
  • 7
    To comlete answer: Spring 3.1 Reference — Passing in lists of values for IN clause. But in Reference was nothing said about: it is possible to pass any Collection. Jan 18, 2012 at 20:36
  • 10
    strange, i get "error code [17004]; Invalid column type" when I try this.
    – Trevor
    Oct 10, 2013 at 3:34
68

I do the "in clause" query with spring jdbc like this:

String sql = "SELECT bg.goodsid FROM beiker_goods bg WHERE bg.goodsid IN (:goodsid)";

List ids = Arrays.asList(new Integer[]{12496,12497,12498,12499});
Map<String, List> paramMap = Collections.singletonMap("goodsid", ids);
NamedParameterJdbcTemplate template = 
    new NamedParameterJdbcTemplate(getJdbcTemplate().getDataSource());

List<Long> list = template.queryForList(sql, paramMap, Long.class);
4
  • 10
    You just posted an answer to a almost three year old question with the same solution as the accepted answer had. Is there any good reason behind this? :-)
    – Malax
    Feb 9, 2012 at 9:20
  • 17
    This answer provides more clarity because it illustrates that the NamedParameterJdbcTemplate is needed for this API... so thanks for the additional detail janwen
    – IcedDante
    Mar 17, 2015 at 16:46
  • @janwen , Thanks for the solution!!! It's working fine as per my requirement!! Dec 10, 2019 at 6:24
  • This solution worked for me when the array of IDs was very large. The accepted answer's solution fails when the array is too large. Sep 3, 2022 at 22:04
20

If you get an exception for : Invalid column type

Please use getNamedParameterJdbcTemplate() instead of getJdbcTemplate()

 List<Foo> foo = getNamedParameterJdbcTemplate().query("SELECT * FROM foo WHERE a IN (:ids)",parameters,
 getRowMapper());

Note that the second two arguments are swapped around.

3
  • 2
    This doesn't seem to be an answer to this question. Should it be a comment on another answer? May 13, 2014 at 3:03
  • 2
    @DaveSchweisguth Two years later, it definitely warrants being an answer.
    – dwjohnston
    Apr 30, 2015 at 1:57
  • getNamedParameterJdbcTemplate() is undefined. need to extend NamedParameterJdbcDaoSupport if you want that method. Feb 10, 2022 at 18:02
2

Refer to here

write query with named parameter, use simple ListPreparedStatementSetter with all parameters in sequence. Just add below snippet to convert the query in traditional form based to available parameters,

ParsedSql parsedSql = NamedParameterUtils.parseSqlStatement(namedSql);

List<Integer> parameters = new ArrayList<Integer>();
for (A a : paramBeans)
    parameters.add(a.getId());

MapSqlParameterSource parameterSource = new MapSqlParameterSource();
parameterSource.addValue("placeholder1", parameters);
// create SQL with ?'s
String sql = NamedParameterUtils.substituteNamedParameters(parsedSql, parameterSource);     
return sql;
1
  • for me this was the only answer that worked as I just wanted to set few placeholders
    – Kapil
    Jan 24, 2020 at 13:14
-3

Many things changed since 2009, but I can only find answers saying you need to use NamedParametersJDBCTemplate.

For me it works if I just do a

db.query(sql, new MyRowMapper(), StringUtils.join(listeParamsForInClause, ","));

using SimpleJDBCTemplate or JDBCTemplate

1
  • 12
    The problem with this solution is, that the content in listeParamsForInClause wont be escaped and makes you vulnerable to SQL injection.
    – Malax
    Oct 1, 2016 at 10:11

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.