"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How can I effectively use IN() SQL queries with Spring's JDBCTemplate?

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

Published on 2024-11-16
Browse:117

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

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 ids = ...;

MapSqlParameterSource parameters = new MapSqlParameterSource();
parameters.addValue("ids", ids);

List 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.

Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3