geeky · java

How to execute IN() SQL in spring jdbcTemplate

So for a long time, I wondered how you’d do the sql IN() using spring jdbcTemplate. Today I had an opportunity to work it out.

Normally I used

List Foos = jdbcTemplate.query("select * from foo where name = ?", 
	new Object[] { "foo1" }, 
	new FooMapper()
);

It’s not too friendly if you do

select * from food where name in ('foo1', 'foo2')

If you wish to use the “where in” sql, there is a pretty elegant way to do it in spring since spring 2.0 actually. I didn’t find out until today.

NamedParameterJdbcTemplate namedParameterJdbcTemplate = new NamedParameterJdbcTemplate(jdbcTemplate);
MapSqlParameterSource parameters = new MapSqlParameterSource();
parameters.addValue("names", Arrays.asList("foo1", "foo2"));
List Foos = namedParameterJdbcTemplate.query("select * from foo where name in (:names)",
	parameters,
	new FooMapper()
);

2 thoughts on “How to execute IN() SQL in spring jdbcTemplate

Leave a comment