views:

1518

answers:

4

Hi all together,

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 substution of prepared statements. I cannot imagine i am the only person who is annoyed by this fact im asking here to get a solution. Thanks a lot in advance!

+2  A: 

I don't think there is, unfortunately.

To concatenate your fields into an IN() clause, you should look at Apache Commons and StringUtils.join().

I know that's not quite the answer you're looking for, but it does simply the the above.

EDIT: yawn (above) has identified the existing method.

Brian Agnew
Not quite what im looking for, but may help to ease the pain. Thanks!
Malax
Yes. Unfortunately I think that's your only option. I've been there before :-(
Brian Agnew
A: 

There's no good way to do it in Spring because there's no good way to do it in JDBC.

duffymo
Thats obvious, i was asking explicitly for JDBCTemplate since there might be some handy helper i am not aware of. :-)
Malax
Not that obvious, because you assumed that Rod Johnson was able to come up with something elegant that you or I would miss. Alas, even the Spring team can't get past this obstacle in JDBC.
duffymo
+9  A: 

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)",
     getRowMapper(), parameters);
yawn
Part of Spring since 2.0 btw
yawn
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
You're welcome!
yawn
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
You should probably insert the values into a temporary table and build the condition using `WHERE NOT EXISTS (SELECT ...)`.
yawn
A: 

The answer above by yawn sounds perfect, but no such version of the query(...) method seems to exist in spring 2.5.6. Was it removed? Or is there some other silly reason I can't find it? Whats the exact signature of the method I should be looking for?

Rasmus Kaj