如何将IN查询与NamedParameterJdbcTemplate一起使用?

How can I use IN query with NamedParameterJdbcTemplate?

提问人:JeonYongWook 提问时间:9/22/2022 最后编辑:Mark RotteveelJeonYongWook 更新时间:9/29/2022 访问量:45

问:

如何将IN查询与NamedParameterJdbcTemplate一起使用?

protected List getList(String sql, Map<String, ?> param) {
    String sql = "select birth from member where gender=:gender and surname in (:surname)";
    List list = this.simpleJdbcTemplate.queryForList(sql, param);
    return list;
}

我把'surname1','surname2'和surname1','surname2放在参数中,所以:surname将是'surname1','surname2',但两者都不起作用。当只有性别参数时,它起作用了。

我该怎么做?

java jdbc spring-jdbc jdbctemplate 命名参数

评论


答:

1赞 alalalala 9/22/2022 #1

如果我们有一个这样的对象:

Class Member {
    String birth;
    String gender;
    String surname;
    //getter & setter
}

然后:

String sql = "select birth from member where gender=:gender and surname in (:surname);";
List<String> surnames = new ArrayList<>();
surnames.add("aaaaa");
surnames.add("bbbbb");
MapSqlParameterSource parameters = new MapSqlParameterSource();
parameters.addValue("surname", surnames);
parameters.addValue("gender", "man");
NamedParameterJdbcTemplate givenParamJdbcTemp = new NamedParameterJdbcTemplate(simpleJdbcTemplate);
// query a list for Member;
List<Member> data = givenParamJdbcTemp.query(sql, parameters, new RowMapper<Member>() {
    @Override
    public Member mapRow(ResultSet rs, int rowNum) throws SQLException {
        Member member = new Member();
        member.setBirth(rs.getString("birth"));
        return member;
    }
}
//just query a list for birth
List<String> data = givenParamJdbcTemp.query(sql, parameters, new RowMapper<String>() {
    @Override
    public String mapRow(ResultSet rs, int rowNum) throws SQLException {
        return rs.getString("birth");
    }
}
0赞 mohammedkhan 9/29/2022 #2

在 Add 中,将要搜索的姓氏添加为 .例如:paramMapCollection

List<String> surnames = new ArrayList<>();
surnames.add("Smith");
surnames.add("Patel");
param.put("surnames", surnames);