I've been trying to save a JSON array in Postgres using Java and a PreparStatement for half an eternity.
I use my own type in Postgres.
Unfortunately I always get a type error message
Here's my Postgres Function to insert data into my table:
CREATE OR REPLACE FUNCTION "Portfolio"."Einfuegen"(
"dokumenteIN" "Portfolio".t_dokumente[],
"finanzenIN" numeric[],
"bildIN" bytea)
RETURNS character varying
LANGUAGE 'plpgsql'
COST 100
VOLATILE
AS $BODY$
BEGIN
INSERT INTO "Portfolio"."Historie" (dokumente,finanzen,bild) VALUES
("dokumenteIN","finanzenIN","bildIN");
return 'Gesichert';
END;
$BODY$;
And my custom type looks like this:
CREATE TYPE "Portfolio".t_dokumente AS
(
inhalt json[]
);
ALTER TYPE "Portfolio".t_dokumente
OWNER TO postgres;
I'm trying to insert some JSON Array data with Java:
for (int i = 0; i < arrayDokus.length(); ++i) {
JSONObject rec = arrayDokus.getJSONObject(i);
String nameBild = rec.getString("Name");
String inhalt = rec.getString("Inhalt");
byte[] in = inhalt.getBytes();
try {
Blob blob = new SerialBlob(in);
JSONObject neuesObjekt = new JSONObject();
neuesObjekt.append("Name", nameBild);
neuesObjekt.append("Inhalt", blob);
where.add(neuesObjekt);
} catch (SerialException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
PGobject jsonObject = new PGobject();
jsonObject.setType("json[]");
jsonObject.setValue(where.toString());
PreparedStatement stmt = con.prepareStatement("SELECT * FROM \"Portfolio\".\"Einfuegen\"
(?::\"Portfolio\".t_dokumente[],?,?)");
stmt.setObject(1, jsonObject);
stmt.setArray(2, f);
stmt.setBinaryStream(3,in);
ResultSet rs = stmt.executeQuery();
con.commit();
[...]
But i got the error:
org.postgresql.util.PSQLException: ERROR: Can't convert type json [] to type "Portfolio" .t_dokumente []
dokumenteis an array of complex, and each complex has one fieldinhalt- an array of jsons, why not use justJSONB?