Is it possible to pass a null parameter to a stored procedure in Java JPA 2.1?

前端 未结 13 1754
孤城傲影
孤城傲影 2020-12-08 15:07

Using the new JPA 2.1 stored procedure call, is there any way to pass a null parameter?

Here is an example usage:

StoredProcedureQuery storedProcedur         


        
13条回答
  •  温柔的废话
    2020-12-08 15:33

    I ran into this same issue. I didn't have control over the stored procedure, so I couldn't modify it to accept default values.

    However, because the database I was using was an Oracle database, I was able to work around this issue by changing the datatype of my stored procedure parameter (in orm.xml) to java.lang.String and then substituting an empty String ("") where it would have been appropriate to use a NULL value. Since Oracle treats empty Strings ("") and NULLs identically, I was able to effectively trick Hibernate into passing a "null" value to the Oracle stored procedure.

    If you don't want to have to resort to writing low-level JDBC code, your stored procedure is not modifiable, and your database is Oracle-based, try this approach. Just be sure that all of your entity manager code treats the parameter as though it were the intended data type (java.math.BigDecimal in my case), and wait until you're setting the parameter value to convert to java.lang.String.

    For example:

    orm.xml:

    
        
        
        
        
        
        
    
    

    Java:

    public void callStoredProc(java.math.BigDecimal myNullableInParam) {
        EntityManager entityManager = EMF.createEntityManager();
        
        StoredProcedureQuery query = entityManager.createNamedStoredProcedureQuery("storedProcName");
        
        query.setParameter("my_nullable_in_param", (myNullableInParam == null ? "" : myNullableInParam.toString()));
        
        // set more parameters, execute query, commit transaction, etc.
    }
    

提交回复
热议问题