代码之家  ›  专栏  ›  技术社区  ›  Robert Munteanu

SimpleJDBCTemplate和空参数

  •  11
  • Robert Munteanu  · 技术社区  · 15 年前

    我使用simplejdbctemplate和mapsqlparametersource的方式如下:

    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 ?

    1 回复  |  直到 15 年前
        1
  •  6
  •   skaffman    15 年前

    他们有一个点-JDBCTemplate不是SQL解释器,它只是替换了您的占位符。

    我建议您使用实用工具方法构造子句,并将其连接到查询字符串:

    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”,但我不认为这是一个选项。