Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to query for an postgres integer array in spring

I am using Java 7 and JDBC template to query a integer array from PostgreSQL. My code is as below:

@Autowired
private JdbcTemplate jdbcTemp;

String SQL = "select item_list from public.items where item_id=1";
List<Integer> ListOfitems=jdbcTemp.queryForList(SQL , Integer.class);

My item_list column is integer[] in PostgreSQL. But when I try like this it throws an error as:

Bad value for type int psql exception

I also tried:

List<List<Integer>> ListOfitems=jdbcTemp.queryForList(SQL , Integer.class);

But it still throws the same exception.

Any help is appreciated.

like image 536
Ricky Avatar asked Aug 12 '26 05:08

Ricky


1 Answers

You can use java.sql.Array.

If you want to get only integer array you can try like this (it works if result contains one row):

String SQL = "select item_list from public.items where item_id=1";
Array l = template.queryForObject(SQL, Array.class);
List<Integer> list = Arrays.asList((Integer[]) l.getArray());

Or use RowMapper

Foo foo = template.queryForObject(SQL, new RowMapper<Foo>(){
        @Override
        public Foo mapRow(ResultSet rs, int rowNum) throws SQLException {
            Foo foo = new Foo();
            foo.setName(rs.getString("name"));
            foo.setIntegers(Arrays.asList((Integer[]) rs.getArray("item_list").getArray()));
            return foo;
        }
    });

Class Foo:

class Foo {
    private String name;
    private List<Integer> integers;

    public String getName() {
        return name;
    }
    // ...
}
like image 131
Egor Avatar answered Aug 14 '26 18:08

Egor



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!