Tuesday 2 August 2016

Call PL/SQL Procedure with 1 2 3 4 ... n OUT parameter in ADF Application


There was a question posted on forums how can we call a procedure from Oracle ADF application with 2 out parameters, i was thinking why just fixed with two output return parameters.

This post also shares how to call a stored procedure in ADF application to and display the same in Oracle ADF application UI.

Stored Procedure to return multiple column(s)
create or replace  PROCEDURE retrieveUser(p_strLogin IN VARCHAR2, cv_1 OUT SYS_REFCURSOR)
  IS
  BEGIN
    open cv_1 for
      select employee_id,first_name,email,last_name from employees where email=p_strLogin;
  END retrieveUser;


Method to call stored procedure on click on call procedure button
    public void storedProcMethod(ActionEvent actionEvent) {
        
        if(null!=getEmailId());
        Boolean b = userDetails(getEmailId());
        if (b != null && b.equals(Boolean.TRUE)) {
            System.out.println("User details found");
        } else {
            System.out.println("User details not found");
        }
    }
//Helper method to call method of AMImpl class and show the same on UI. 
    public boolean userDetails(String userId) {
        AppModuleImpl amImpl = (AppModuleImpl) resolvElDC("AppModuleDataControl");
        String sql = "retrieveUser(?,?)";
        String[] params = { userId };

        List list = amImpl.callProcedureReturnList(sql, params);

        if (list.size() > 0) {

            Map value = (Map) list.get(0);
             System.out.println("First Name"+value.get("FIRST_NAME").toString());
            System.out.println("EMPLOYEE_ID"+value.get("EMPLOYEE_ID").toString());
            System.out.println("First Name"+value.get("EMAIL").toString());
            System.out.println("EMPLOYEE_ID"+value.get("LAST_NAME").toString());
            this.firstBinding.setValue(value.get("FIRST_NAME"));
            this.empIdBinding.setValue(value.get("EMPLOYEE_ID"));
            this.lastNameBinding.setValue(value.get("LAST_NAME"));
            AdfFacesContext.getCurrentInstance().addPartialTarget(lastNameBinding);
            AdfFacesContext.getCurrentInstance().addPartialTarget(firstBinding);
            AdfFacesContext.getCurrentInstance().addPartialTarget(empIdBinding);


            return true;
        }
   
        return false;
    }
//Helper method to get instance of AM
    private Object resolvElDC(String data) {
            FacesContext fc = FacesContext.getCurrentInstance();
            Application app = fc.getApplication();
            ExpressionFactory elFactory = app.getExpressionFactory();
            ELContext elContext = fc.getELContext();
            ValueExpression valueExp =
                elFactory.createValueExpression(elContext,"#{data." + data + ".dataProvider}", Object.class);
            return valueExp.getValue(elContext);
        }
//AMimpl method to call stored procedure and return out parameters(s) as list which would be helpful in returning many output variables.
    public List callProcedureReturnList(String sql, Object[] params) {
            String sql2 = "begin " + sql + "; end;";
            CallableStatement stmt = null;
            try {
                // 1. Create a JDBC PreparedStatement for
                stmt = getDBTransaction().createCallableStatement(sql2, 0);

                // 2. Set the parameters
                for (int i = 0; params != null && i < params.length; i++) {
                    if (params[i] != null && params[i].getClass().getName().equals("java.util.Date")) {
                        Date dd = (Date)params[i];
                        if (dd != null)
                            stmt.setDate(i + 1, new java.sql.Date(dd.getTime()));
                    } else {
                        stmt.setObject(i + 1, params[i]);
                    }
                }


                int result_pos = 1;
                if (params != null)
                    result_pos = params.length + 1;
                stmt.registerOutParameter(result_pos, OracleTypes.CURSOR);

                // 4. Execute the statement
                stmt.executeUpdate();

                // 5. Return
                ResultSet rs = ((OracleCallableStatement)stmt).getCursor(result_pos);
                return resultSetToList(rs);
            } catch (SQLException e) {
                throw new JboException(e);
            } finally {
                if (stmt != null) {
                    try {
                        // 5. Close the statement
                        stmt.close();
                    } catch (SQLException e) {
                        // TODO: log
                        throw new JboException(e);
                    }
                }
            }
        }

//Helper method to populate column,data result set
    private  List<Map<String,Object>> resultSetToList(ResultSet rs) throws SQLException {
            ResultSetMetaData rsmd = rs.getMetaData();
            Vector<String> cols = new Vector<String>();
         
            for(int i=1; i <= rsmd.getColumnCount(); i++) {
                cols.add(rsmd.getColumnName(i));
            }
         
            List<Map<String, Object>> list = new Vector<Map<String, Object>>();
            if (rs != null) {
                while(rs.next()) {
                    HashMap<String, Object> map = new HashMap<String, Object>();
                    for(int i=0; i < cols.size(); i++) {
                        map.put(cols.get(i), rs.getString(i+1));
                    }
                    list.add(map);
                }          
            }
            return list;
        }

No comments:

Post a Comment