How to generate a dynamic “in (…)” sql list through Spring JdbcTemplate?

前端 未结 3 895
自闭症患者
自闭症患者 2020-12-01 06:23

Is it possible to generate arbitrary \"in ()\" lists in a SQL query through Jdbc template:

example:

\"select * from t where c in (#)\" , However \'#\' could

3条回答
  •  一个人的身影
    2020-12-01 07:07

    Yes, it's possible in Spring if you use NamedParameterJdbcTemplate or SimpleJdbcTemplate with named parameters. List parameter can be set as a java.util.List:

    List list = new ArrayList();
    
    list.add("A");
    list.add("B");
    list.add("C");
    
    List result = simpleJdbcTemplate.query("SELECT * FROM t WHERE c in (:list)",
        new RowMapper() { ... },
        Collections.singletonMap("list", list));
    

    In this case Spring internally creates the SQL query with the required number of placeholders based on the size of the actual list when replacing named parameters with ?s.

提交回复
热议问题