Effective IN() SQL Queries with Spring's JDBCTemplate
You have an IN() query that currently has you building a clause with multiple lines of code:
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()); }
You seek a more elegant way that is similar to prepared statements' parameter substitution.
Using a Parameter Source
To achieve your desired elegance, you can use 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());
NamedParameterJdbcTemplate
Note that this only works if getJdbcTemplate() returns an instance of type NamedParameterJdbcTemplate.
The above is the detailed content of How can I effectively use IN() SQL queries with Spring's JDBCTemplate?. For more information, please follow other related articles on the PHP Chinese website!