2012-04-13 4 views
0

Possible Duplicate:
How to generate a dynamic “in (…)” sql list through Spring JdbcTemplate?안전하게 쿼리

나는 자바에서 MSSQL에서 IN() 조항에 대한 ID 목록을 준비하기 위해 노력하고있어 대한 쉼표로 구분 된 목록을 준비합니다. 아래 코드가 작동해야하지만 오류가 발생합니다. java.sql.SQLException : nvarchar 값 '1,2'를 int 유형의 데이터로 변환 할 때 변환에 실패했습니다.

문자열을 전달할 때 정수와 같은 이유는 무엇입니까? 어떤 통찰력도 좋을 것입니다.

는 또한 행운을 당신은 템플릿 ID의 컬렉션을 준비하고지도에 전달해야

//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); 
+1

는'의 int보다는 문자열의 컬렉션을 수 templateIds'하지 않나요? 문자열 솔루션이 작동하더라도 솔루션은 매우 안전하지 않을 것입니다. 'template.getId()'의 쉼표가 잘못된 값을 도입 할 것이기 때문입니다. – biziclop

+0

그래, @ biziclop 언급 한 바와 같이 - 가능한 경우 int []를 매개 변수로 사용해보십시오. – JMelnik

+0

이것 좀보세요 : http://stackoverflow.com/questions/2810418/how-to-execute-query-with-in-clause-in-spring – Vadzim

답변

2

template.getId().toString()template.getId()을 변경 시도했습니다. 문자열 구분 데이터가 컬렉션을 예상대로 작동하지 않을 수 있습니다.

=======================

List templateIds = new ArrayList(); 
templateIds.add(template.getId()); 

---- 
--- 

queryMap.put("templateIds", templateIds); 
관련 문제