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 Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s