[英]How to convert array of composite type to array of java objects with jdbc and Postgres?
I have an array of composite type. 我有一个复合类型的数组。 Let's say it looks like this: 假设它看起来像这样:
CREATE TYPE hobbie AS (
name VARCHAR,
description VARCHAR
);
CREATE TABLE person (
id SERIAL,
hobbie hobbie[]
);
Now I need to retrieve hobbies of person from postgres and convert them into java object which looks like this: 现在,我需要从postgres检索人的爱好并将其转换为如下所示的java对象:
public class Hobbie {
String name;
String description;
}
The only thing which I was able to do with jdbc is to convert array get to result set with hobbies as String like this ("basketball","the best game")
. 我唯一可以用jdbc进行的事情就是将数组转换成带有这样的String兴趣爱好的结果集("basketball","the best game")
。 How can I convert it to java object using jdbc? 如何使用jdbc将其转换为java对象?
UPDATE: 更新:
Here is my code to work with postgres array using jdbc: 这是我的使用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
}
Query the table like this 像这样查询表
SELECT (r).* FROM (SELECT unnest(hobbie) AS r
from person) AS hobbies;
It'll output the hobbies as if they were a table. 它将把兴趣爱好当作一张桌子输出。 JDBC translation should rather straight-forward from there. JDBC转换应该从那里直接进行。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.