如何在Spring JDBCTemplate 中提供SQL cast?

How to provide SQL cast in Spring JDBCTemplate?

我在 postgres 中有一个 table 存储 IP 地址(inet 数据类型)。我查询如下 -

NamedParameterJdbcTemplate namedParameterJdbcTemplate = new NamedParameterJdbcTemplate(jdbcTemplate);


    Map<String, Object> params = new HashedMap();
        Collection<Object> ipList = new LinkedList<>();
        ips.add("1.2.3.4");
        ips.add("5.6.7.8");

    namedParameterJdbcTemplate.query("select * from myTable source_ip in (:ipList)",
            params, new RowMapper<Object>() {
              @Nullable @Override public Object mapRow(ResultSet rs, int rowNum) throws SQLException {
                System.out.println(rs.toString());
                return null;
              }
            });

上面的代码片段给了我数据库异常- No operator matches the given name and argument type(s). You might need to add explicit type casts.

我查看了 NamedParameterJdbcTemplate.class 源代码,发现无法指定参数数据类型。

有什么想法吗?

现在我已经扩展了 NamedParameterJdbcTemplate 中的扩展方法 getPreparedStatementCreator,这样它将一个 sql 强制转换变量附加到“?”在准备好的声明中

我猜你错过了将 ipList 添加到参数映射:

Map<String, Object> params = new HashedMap<>();
Collection<Object> ipList = new ArrayList<>();
ipList.add("1.2.3.4");
ipList.add("5.6.7.8");
params.put("ipList", ipList);

但我建议使用:

MapSqlParameterSource params = new MapSqlParameterSource();
params.addValue("ipList", Arrays.asList("1.2.3.4", "5.6.7.8"));