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.
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;
}
// ...
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With