2009-07-21 26 views
10

我使用了SimpleJdbcTemplate和MapSqlParameterSource在如下因素的方法:SimpleJdbcTemplate類和空參數

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

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

typeId(這是一個Long)是null,那麼查詢看起來下列方式:

SELECT id FROM XXX WHERE typeId = null 

,而我希望它產生

SELECT id FROM XXX WHERE typeId IS NULL 

我已經reported this issue和響應是

你將不得不提供基於您的查詢參數的適當的SQL語句。

因此,我的代碼散佈着空檢查。

是否有處理髮送到SimpleJdbcTemplate空參數更優雅的方式?

回答

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); 

不是很漂亮。或者,也許你可以配置MySQL允許「= NULL」,但我不認爲這是一種選擇。

+0

將它的工作,如果是NamedParameterJdbcTemplate是用來代替了SimpleJdbcTemplate? – 2016-09-27 06:02:15