可能重复:
How to generate a dynamic “in (…)” sql list through Spring JdbcTemplate?
我正在尝试为java中的MsSQL中的IN()
子句准备一个ID列表。我有下面的代码看起来应该可以工作,但它抛出了错误:java.sql.SQLException:将nvarchar值'1,2'转换为数据类型int时转换失败。
当我传递一个字符串时,我完全不知道为什么它会像整数一样尝试它。任何见解都会很棒。
我也尝试将template.getId()
更改为template.getId().toString()
而没有运气
//JOINs
Collection<Template> templates = search.getTemplateCollection();
if (templates != null && templates.size() > 0) {
searchQuery.append("INNER JOIN dbo.content_to_template ON content_to_template.template_id IN (:templateIds) AND content_to_template.content_id = content.id ");
StringBuilder templateIds = new StringBuilder();
for (Template template : templates) {
if (templateIds.length() == 0) {
templateIds.append(template.getId());
} else {
templateIds.append(",").append(template.getId());
}
}
queryMap.put("templateIds", templateIds.toString());
}
return this.namedjdbcTemplate.query(searchQuery.toString(), new MapSqlParameterSource(queryMap), this.contentRowMapper);
答案 0 :(得分:2)
您需要准备一组模板ID并将其传递给地图。 字符串分隔的数据可能无法正常工作,因为它需要一个集合。
=======================
List templateIds = new ArrayList();
templateIds.add(template.getId());
----
---
queryMap.put("templateIds", templateIds);