14 September, 2016

How to call an Oracle PL/SQL function from a Java Hibernate application

While the Hibernate framework for Java handles basic SQL (as HQL) calls, and can also deal with Oracle PL/SQL procedures, it doesn't have a method for directly calling a PL/SQL function, and retrieving the return value. Here is an approach that appears to work.

Notice that, instead of the createQuery() method I have used the createSQLQuery() method. This allows me to use a PL/SQL call, instead of being restricted to HQL. The advantages of this approach is that it lets me reference Oracle's DUAL table without receiving an unmapped error, and it also lets me use a prepared statement to map in my parameters, thus trapping out SQL injection attacks.

The downside is that, because it is using a PL/SQL query instead of an HQL query, it is not DBMS agnostic, and so not portable.

 


-- Oracle PL/SQL function
CREATE OR REPLACE FUNCTION get_some_string_fnc (

    p_argument IN INTEGER
)
RETURN VARCHAR2
IS

BEGIN
    v_result VARCHAR2(64) := NULL
    -- Do some stuff
    RETURN(v_result);

END;




/*

 * Java code in DAO object
 * Hibernate does not handle calling functions very simply,

 * so this bit is Oracle PL/SQL specific, with the DUAL reference,
 * which requires using createSQLQuery() instead of the more
 * portable createQuery() that uses HQL.
 */
String funString = "SELECT get_some_string_fnc(:p_argument) FROM DUAL";
Query funCall = session.createSQLQuery( funString );
int argument = 1234;
String funRslt;
try {
    funCall.setParameter( "p_argument", argument );
    funRslt = (String)funCall.uniqueResult();
} catch ( HibernateException he ) {
    log.error( he.toString() );
    funRslt = "unavailable";
}

No comments:

Post a Comment