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?
5098 views
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?
5098 views
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 t.id 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: https://www.baeldung.com/spring-jdbctemplate-in-list