Home > Java > javaTutorial > How can I effectively use IN() SQL queries with Spring's JDBCTemplate?

How can I effectively use IN() SQL queries with Spring's JDBCTemplate?

Mary-Kate Olsen
Release: 2024-11-25 01:53:10
Original
677 people have browsed it

How can I effectively use IN() SQL queries with Spring's JDBCTemplate?

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

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());
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template