2009-07-21 7 views
10
나는 folowing 방법 인 SimpleJdbcTemplate와 MapSqlParameterSource을 사용하고

:인 SimpleJdbcTemplate 및 널 (null) 매개 변수

SELECT id FROM XXX WHERE typeId = null 
: (A Long입니다) typeIdnull 경우

은, 다음 쿼리는 다음과 같은 방법으로 보인다

MapSqlParameterSource parameterSource = new MapSqlParameterSource(); 
parameterSource.addValue("typeId", typeId, Types.BIGINT); 

List<Long> ids = _jdbcTemplate.query(_selectIdByParameters, new EntityIdRowMapper(), parameterSource); 

나는 그것이 생성하는 기대 반면

SELECT id FROM XXX WHERE typeId IS NULL 
,

나는 reported this issue를했는데 응답이

당신은 당신의 쿼리 매개 변수에 따라 적절한 SQL 문을 제공해야합니다이었다.

그리고 결과적으로 내 코드는 null 검사로 흩어져 있습니다.

SimpleJdbcTemplate으로 보내는 null 매개 변수를 처리하는보다 세련된 방법이 있습니까?

답변

6

JdbcTemplate은 SQL 인터프리터가 아니며 단순히 자리 표시자를 대체합니다.

나는 당신이 유틸리티 메소드와 절을 구성하고, 쿼리 문자열로 CONCAT 제안 :

String createNullCheckedClause(String column, Object value) { 
    String operator = (value == null ? "is" : "="); 
    return String.format("(%s %s ?)", column, operator); 
} 

... 

String query = "select * from table where " + createNullCheckedClause("col", x); 

하지 아주 예쁜. 또는, 아마도 "= NULL"을 허용하도록 MySQL을 구성 할 수 있지만, 이것이 옵션이라고 생각하지 않습니다.

+0

simplejdbctemplate 대신 namedparameterjdbctemplate을 사용하면 작동합니까? –