Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

calling oracle PL/SQL function in java - Invalid column type error

Tags:

java

jdbc

I want to call a plsql function from java class but that function (isValidPeriod) return a boolean datat type and JDBC doesn't support it

like image 888
Prashant Avatar asked Dec 01 '22 21:12

Prashant


2 Answers

Starting in the 12.2 version of the JDBC-thin driver, there is native support for the PLSQL BOOLEAN type.

For IN parameters you would do:

CallableStatement cstmt = conn.prepareCall(sql);
// Make the driver send the Java "false" boolean as a PLSQL BOOLEAN type:
cstmt.setObject(2, false, OracleTypes.PLSQL_BOOLEAN);
...
cstmt.execute();
...

and for OUT parameters you do:

CallableStatement cstmt = conn.prepareCall(sql);
// The driver should expect a PLSQL BOOLEAN type for the first OUT argument
// of the PLSQL procedure:
cstmt.registerOutParameter(1, OracleTypes.PLSQL_BOOLEAN);
cstmt.execute();
...
boolean likeTrump = cstmt.getBoolean(1);
like image 41
Jean de Lavarene Avatar answered Dec 04 '22 11:12

Jean de Lavarene


There is a simple workaround for that restriction, which does not require a wrapper function, simply wrap the boolean function itself in a CASE statement and use an Integer for binding:

stmt = conn.prepareCall(
          "BEGIN"
        + " ? := CASE WHEN (myBooleanFuncInOracle()) "
        + "       THEN 1 "
        + "       ELSE 0"
        + "      END;"
        + "END;");

stmt.registerOutParameter(1, Types.INTEGER);

// exec
stmt.execute();

// get boolean from Integer
boolean myBool = (stmt.getInt(1) == 1);

Very useful if you can't or don't want to change your function or even can't create a wrapper function, i.e. in legacy DBs.

like image 68
GWu Avatar answered Dec 04 '22 11:12

GWu