简体   繁体   English

SQL 使用 JDBCTemplate 时,`IN` 在 Spring Boot 中不起作用

[英]SQL `IN` not work in Spring Boot when using JDBCTemplate

I've JDBC template object and I try run query to database for delete but I can't run this query.我有 JDBC 模板 object,我尝试对数据库运行查询以进行删除,但我无法运行此查询。 How can I do it?我该怎么做?

jdbcTemplate.update("delete from `message` where `id` IN (:ids) and `from` = ?;", new Integer[] {1, 2}, 1);

--- ADDED - - 添加

public static final Map<String, String> SQL = new HashMap<String, String>() {{
        put("removeMessages", "delete from `message` where `id` IN ( :ids ) and `@` = :userId ;");
    }};


    public int removeMessages(@NonNull Integer[] ids, @NonNull Integer userId, boolean asSender) {
        MapSqlParameterSource parameters = new MapSqlParameterSource().addValue("ids", Arrays.asList(ids)).addValue("userId", userId);
        String sql = SQL.get("removeMessages").replace("@", asSender ? "from" : "to");
        return getInstance(MainSQL.class).query(sql, parameters);
    }

You need to use NamedParameterJdbcTemplate for named parameters.您需要对命名参数使用 NamedParameterJdbcTemplate。 Try to use this code:尝试使用此代码:

List<Integer> ids= Arrays.asList(1,2);
MapSqlParameterSource parameters = new MapSqlParameterSource();
parameters.addValue("ids", ids);
parameters.addValue("from",1);
namedParameterJdbcTemplate.update("delete from `message` where `id` IN (:ids) and `from` = :from;",parameters);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM