I want to specify multiple values for SQL IN clauses with named parameters.

Asked 2 years ago, Updated 2 years ago, 99 views

The framework uses Spring.
NamedParameterJdbcTemplateWould it be possible to run SQL by arranging multiple values for the following placeholders (:id portion) using the class?I would like to arrange several userId's from the table in the placeholder below so that SQL can run, but I don't know how to implement it.
■ SQL statement with placeholder

//Defining SQL
String sql = "select name from sampletbl where id in(:id)";

java spring

2022-09-30 16:19

1 Answers

If the parameters passed to the in clause are a collection such as Set, a placeholder will be created for a few minutes and the value will be saved.

Set<Integer>ids=new HashSet<>();
    ids.add(1);
    ids.add(2);
    ids.add(3);

    MapSqlParameterSource parameters = new MapSqlParameterSource();
    parameters.addValue("ids", ids);
    List<String>result=this.namedJdbcTemplate.query("select name from sampletbl where id in(:ids), parameters, (resultSet, i)->resultSet.getString("name"));
    System.out.println(result);

When running, the SQL will be as follows:

 select name from sampletbl where id in (?,?,?)


2022-09-30 16:19

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.