javaarrayspostgresqljdbcstored-functions

How to get PSQL function to return VARCHAR[] and process it in JDBC?


I am writing a function that removes all the acts for a given Gig

CREATE OR REPLACE FUNCTION removeAllActsFromGig(gGigId INTEGER) RETURNS VARCHAR[]

It should return all the customer names that are affected by this cancellation and set the cost of their ticket to 0.

There is a ticket table with fields gigID, CustomerName and cost.

I have declared a VARCHAR array, a, and am trying to insert the result of the below query into the array and return it.

a VARCHAR[]

UPDATE ticket SET Cost = 0 WHERE gigID = gGigID RETURNING CustomerName INTO a;

On a processing level, in Java, I would like to cast the array returned as an array of Strings. There is some documentation on this e.g: Using Array Objects

Here's the corresponding JDBC code:

removeAllActsFromGig = conn.prepareCall("{? = call removeAllActsFromGig(?) }");
removeAllActsFromGig.registerOutParameter(1, java.sql.Types.ARRAY);
removeAllActsFromGig.setInt(2, gigID);     
removeAllActsFromGig.execute();
String[] result = (String[])removeAllActsFromGig.getArray(1);

However, upon attempting to cast the result I am getting the error

java.sql.Array cannot be converted to java.lang.String[]

Anyone have any ideas on what I can do?


Solution

  • getArray() returns a java.sql.Array, not a Java array. You must call getArray() on that instance. The result of that can be cast to a Java array

    java.sql.Array array = removeAllActsFromGig.getArray(1);
    String[] result = (String[])array.getArray();
    

    You also don't need a CallableStatement to use a Postgres function. A good old PreparedStatement and executeQuery() will work just fine

    PreparedStatement removeAllActsFromGig = 
            conn.prepareStatement("select removeAllActsFromGig(?)");
    
    removeAllActsFromGig.setInt(1, gigID);     
    ResultSet rs = removeAllActsFromGig.executeQuery();
    if (rs.next()) {
       Array array = rs.getArray(1);
       ...
    }