Spring使用IN子句将NamedParameterJdbcTemplate删除

时间:2014-06-23 08:36:16

标签: java spring jdbc jdbctemplate

当我尝试执行删除操作时,items设置为List<String>NamedParameterJdbcTemplate似乎没有为生成的语句的所有占位符设置值。

public class DBTest {

    public static void main(String[] args) {
        BasicDataSource basicDataSource = new BasicDataSource();
        basicDataSource.setDriverClassName("com.mysql.jdbc.Driver");
        basicDataSource.setUrl("jdbc:mysql://localhost:3306/test?rewriteBatchedStatements=true");
        basicDataSource.setUsername("root");
        basicDataSource.setPassword("qwedsa");

        NamedParameterJdbcTemplate template = new NamedParameterJdbcTemplate(new JdbcTemplate(basicDataSource));

        ImmutableMap<String, ?> param = ImmutableMap.of("items", newArrayList("a", "b", "c"), "user_id", 1);
        Map<String, ?>[] params = new Map[]{param};
        template.batchUpdate("delete from sample where col1 in (:items) and user_id = :user_id", params);
    }
}

错误

bad SQL grammar [delete from sample where col1 in (?, ?, ?) and user_id = ?];
nested exception is java.sql.SQLException: No value specified for parameter 3

NamedParameterJdbcTemplate是否展开了删除语句的列表?

1 个答案:

答案 0 :(得分:1)

您可以将代码简化为:

public static void main(String[] args) {
        BasicDataSource basicDataSource = new BasicDataSource();
        basicDataSource.setDriverClassName("com.mysql.jdbc.Driver");
        basicDataSource.setUrl("jdbc:mysql://localhost:3306/test?rewriteBatchedStatements=true");
        basicDataSource.setUsername("root");
        basicDataSource.setPassword("qwedsa");

        NamedParameterJdbcTemplate template = new NamedParameterJdbcTemplate(basicDataSource);

        ImmutableMap<String, ?> param = ImmutableMap.of("items", newArrayList("a", "b", "c"), "user_id", 1);
        template.update("delete from sample where col1 in (:items) and user_id = :user_id", param);
    }

工作得很好