开发者

How to execute query with IN clause in spring?

开发者 https://www.devze.com 2022-12-29 17:56 出处:网络
I have following code : try { MapSqlParameterSource parameters = new MapSqlParameterSource(); parameters.addValue(\"ids\", year);

I have following code :

try {
    MapSqlParameterSource parameters = new MapSqlParameterSource();
    parameters.addValue("ids", year);

    return this.template.getJdbcOperations().query(
            "SELECT * FROM INCOME WHERE PROVNUM=? AND FISCALDATE IN ( :ids )", this.rowMapper, parameters);   
} catch (EmptyResultDataAccessException ex) {
    return null;
}

B开发者_如何转开发ut i am not able to send the value for PROVNUM. how to do that?

need help, thanks.


It looks like you are mixing named and position parameters. It's best to use one or the other, but not both.

Try

MapSqlParameterSource parameters = new MapSqlParameterSource();
parameters.addValue("ids", year);
 parameters.addValue("provnum", provnum);

return this.template.getJdbcOperations().query(
                    "SELECT * FROM INCOME WHERE PROVNUM=:provnum AND FISCALDATE IN ( :ids )", this.rowMapper, parameters);

After your comment, I see that you are using the wrong overload of the query() method: there are quite a few to choose from, so it's not surprising a few errors can creep in!

You need to call

return this.template.getJdbcOperations().query(
       "SELECT  ... etc.", parameters, this.rowMapper);

In your original call, you are calling the version query(String sql, RowMapper mapper, Object... params) that expects literal parameters. The revised call is query(String sql, SqlParameterSource params, RowMapper mapper) - the SqlParamtersSource as the second argument is the key. Also, just worth checking that that you are using NamedParameterJdbcTemplate.


Just use a named parameter for "provnum" also:

String sql = "SELECT * FROM INCOME WHERE PROVNUM=:provnum AND FISCALDATE IN (:ids )"
MapSqlParameterSource parameters = new MapSqlParameterSource();
parameters.addValue("ids", year);
parameters.addValue("provnum", ...);
return template.getJdbcOperations().query(sql, rowMapper, parameters);
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号