我有一个复合类型的数组。让我们说它看起来像这样:
CREATE TYPE hobbie AS (
name VARCHAR,
description VARCHAR
);
CREATE TABLE person (
id SERIAL,
hobbie hobbie[]
);
现在我需要从postgres中检索人的爱好并将它们转换为java对象,如下所示:
public class Hobbie {
String name;
String description;
}
我能用jdbc做的唯一事情是将数组get转换为带有爱好的结果集,就像这个("basketball","the best game")
一样。如何使用jdbc将其转换为java对象?
更新
这是我使用jdbc处理postgres数组的代码:
ResultSet hobbies = rs.getArray("hobbies").getResultSet
while (hobbies.next()){
hobbies.getString(1) // returns some index or I don't know
hobbies.getObject(2) // returns PgValue with value == String ("basketball","the best game")
hobbies.getObject(2) // obviously returns String with the same value
hobbies.getArray(2) // returns something strange
hobbies.getObject(2, Hobbie.class) // throws unsupported conversion to class com.test.Hobbie. Maybe there is a way to register custom converter, but I didn't find any
}
答案 0 :(得分:2)
像这样查询表
SELECT (r).* FROM (SELECT unnest(hobbie) AS r
from person) AS hobbies;
它会像爱好者一样输出爱好。 JDBC转换应该直接从那里开始。