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

前端 未结 13 1721
孤城傲影
孤城傲影 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:41

    You can create a method to positively enable all the calling parameters as the code below, it also works fine in case your StoredProcedureQuery contains out parameters. This helps you don't break the null parameter checking somewhere.

    public void setStoreProcedureEnableNullParameters(StoredProcedureQuery storedProcedureQuery) {
        if (storedProcedureQuery == null || storedProcedureQuery.getParameters() == null)
            return;
    
        for (Parameter parameter : storedProcedureQuery.getParameters()) {
            ((ProcedureParameterImpl) parameter).enablePassingNulls(true);
        }
    }
    

    Then call

    StoredProcedureQuery storedProcedure = entityManager.createStoredProcedureQuery("your_store_procedure")
        .registerStoredProcedureParameter("Param_1", String.class, ParameterMode.OUT)
        .registerStoredProcedureParameter("Param_2", String.class, ParameterMode.IN)
        .registerStoredProcedureParameter("Param_3", String.class, ParameterMode.IN);
    
    // Remember you must call before setting the value for the parameters
    setStoreProcedureEnableNullParameters(storedProcedure);
    
    storedProcedure
        .setParameter("Param_2", null)
        .setParameter("Param_3", "Some value");
    storedProcedure.execute();
    
    String outValue = (String) storedProcedure.getOutputParameterValue("Param_1");
    

提交回复
热议问题