在带有 Spring-boot 的 postgres 中使用整数数组

Using Integer Array in postgres with Spring-boot

我正试图从浏览器接受一个列表,并在对 postgres 数据库的 SQL 查询中使用它。我有以下代码片段,试图显示我为此所做的功能。一些变量已经更改,以防出现差异。

static public List<Map<String,Object>> fetch(NamedParameterJdbcTemplate jdbcTemplate, List<Integer> id){
    List<Map<String,Object>> result= new ArrayList<>();
    String sql = "select * from lookup where id && ARRAY[ :ids ]";
    MapSqlParameterSource parameters = new MapSqlParameterSource();
    parameters.addValue("ids",id, Types.INTEGER);
    result= jdbcTemplate.query(sql,
            parameters,
            new RowMapper<Map<String,Object>>() { ...
            }
    )
}

查找表 id 字段是一个 postgress 数组,因此我需要使用 && 和数组函数

此函数由许多不同的端点调用并传递 NamedParameterJdbcTemplate 以及整数列表。我遇到的问题是,如果列表中的任何整数小于 100,我会收到以下消息

Bad value for type int : {20}

是否有其他方法或解决此错误的方法?

编辑:

它似乎是作为答案提到的问题的一部分,但也使用了

rs.getInt(col) 

而不是

rs.getArray(col)

我在 SQL 中看到一个错误,之后可能是 API 的错误选择。首先在查询中:

select * from lookup where id && ARRAY[ :ids ]

要绑定数组参数,它不能放在 ARRAY 构造函数中,而是需要像这样使用 JDBC 绑定:

select * from lookup where id && ?

如您所见,我在这些示例中没有使用命名参数,因为 NamedParameterJdbcTemplate 不提供获取 java.sql.Connection 对象或其代理的路径。如果您改用 JdbcOperations 接口,则可以通过 PreparedStatementSetter 访问它。

public static List<Map<String,Object>> fetch(NamedParameterJdbcTemplate jdbcTemplate, List<Integer> idlist){
    List<Map<String,Object>> result= new ArrayList<>();
    String sql = "select * from lookup where id && ?";
    final Integer[] ids = idlist.toArray(new Integer[0]);
    PreparedStatementSetter parameters = new PreparedStatementSetter() {
        @Override
        void setValues(PreparedStatement stmt) {
            Connection conn = stmt.getConnection();
            // this can only be done through the Connection
            java.sql.Array arr = conn.createArrayOf("integer", ids);
            // you can use setObject(1, ids, java.sql.Types.ARRAY) instead of setArray
            // in case the connection wrapper doesn't pass it on to the JDBC driver
            stmt.setArray(1, ids);
        }
    };
    JdbcOperations jdo = jdbcTemplate.getJdbcOperations();
    result= jdo.query(sql,
            parameters,
            new RowMapper<Map<String,Object>>() { ...
            }
    )
}

代码中可能有错误,因为我通常使用不同的一组 API,并且您需要在那个 setValues 函数中为 java.sql.SQLException 使用 try-catch 块, 但你应该能够从这里开始处理它。