我正在尝试加入一个表,该表可能具有给定id的多个条目,并在数组中聚合与此id对应的行。在SQL查询中如下所示:
SELECT * from data
LEFT JOIN (select id, array_agg(row(foo, bar)) AS foo_bar_data from foo_bar_table group by id) AS temp using(id)
这按预期工作,但我在JDBC中读取结果时遇到问题。
ResultSet rs = st.executeQuery(...)
Array a = rs.getArray("foo_bar_data")
// Now I want to iterate over the array, reading the values foo and bar of each item.
到目前为止,我的努力总是以一个
Method org.postgresql.jdbc4.Jdbc4Array.getArrayImpl(long,int,Map) is not yet implemented.
例外而告终。如何遍历a
,检索值foo
和bar
?编辑:我还应该提到,
foo
和bar
不是同一类型的。 最佳答案
PostgresJDBC驱动程序不支持任何东西,除了基本类型(数字、日期/时间戳、字符串)作为JDBC数组。您可以调用array_agg
两次并在每行上获取两个数组:
try (Connection db = DriverManager.getConnection("jdbc:postgresql://localhost:5432/postgres", "postgres", "postgres");
ResultSet rs = db.createStatement().executeQuery("select array_agg(i), array_agg(s) from (select 1 i, 'a' s union select 2 i, 'b' s) t")) {
rs.next();
System.out.println(Arrays.toString((Object[]) rs.getArray(1).getArray()));
System.out.println(Arrays.toString((Object[]) rs.getArray(2).getArray()));
}