Ask Question

JDBCTemplate with list of IDs as parameter for IN statement

I would like to pass a list of IDs as a parameter for an IN statement in my JDBCTemplate. What is the best way to achieve this?



Authorยดs Dominik Sumer image

Dominik Sumer

Last edited on

1 Answer available

Best answer

Not sure if it is the best answer, because that may also differ for various use cases. But for me it worked very well with using a NamedJDBCTemplate and passing a SqlParameterSource object with the desired List of strings as parameter.

Imho this is the most straight-forward solution because you just pass your List and JDBC takes care of safely creating the correct query output.

Here is the snippet:

String myQuery = "select name from table t where t.test = :firstParam and IN (:ids)";

SqlParameterSource params = new MapSqlParameterSource()
                              .addValue("firstParam", "simple_string")
                              .addValue("ids", List.of(1, 2, 3));

new NamedParameterJdbcTemplate(myDataSource).query(myQuery, params, resultSet -> {
  // do something with the resultSet

Baeldung has a very nice, descriptive post on this: