Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Easy way to call stored procedure in Java

When call a stored procedure I use this code:

    connection = getConnection();
    stmt = connection.prepareCall("{call MPLOGIN (?, ?, ?, ?, ?, ?)}");
    stmt.setString("VUSCD", uscd);
    stmt.setString("VPWD", pwd);
    stmt.setString("VPCSQ", pcsq);
    stmt.setString("VHWID", hwid);
    stmt.registerOutParameter("VLOGID", OracleTypes.VARCHAR);
    stmt.registerOutParameter("VKQ", OracleTypes.VARCHAR);
    stmt.execute();
    String vlogid = stmt.getString("VLOGID");
    String vkq = stmt.getString("VKQ");

write this boring wrapper for few procedure is not problem but if there are hundreds of procedure, it is really a nightmare Is there any easier way to call store procedure than this way? Edit: I think a code generator which use the procedure's parameters from DB is the elagant way but I google for nothing in java

like image 428
yelliver Avatar asked Oct 23 '25 21:10

yelliver


2 Answers

You could, maybe create a generic wrapper, something along these lines:

public Map<String, String> SPWrapper(String call, Map<String, String> inParams, Map<String, OracleTypes> outParams)
{
    connection = getConnection();
    try 
    {
        stmt = connection.prepareCall(call);
        for(String inParam : inParams.keys())
        {
            stmt.setString(inParam, inParams.get(inParam));
        }
        for(String outParam : outParams.keys())
        {
            stmt.registerOutParameter(outParam, outParams.get(outParam));
        }

        stmt.execute();

        Map<String,String> results = new HashMap<String, String>();
        for(String outParam : outParams.keys())
        {
            results.put(outParam, stmt.getString(outParam));
        }

        return results;
    }
    catch (Exception e)
    {
        //LOG Exception
        return new HashMap<String, String>();
    }
    finally
    {
        connection.close();   //Do not leave connections open.
    }
}

You would still need to pass in the call and declare the variables, but at least you now have one generic wrapper to handle all your calls.

like image 93
npinti Avatar answered Oct 25 '25 10:10

npinti


I like to use the MyBatis data mapper framework for such problems. An extensive example for working with MyBatis and stored procedures can be found at http://loianegroner.com/2011/03/ibatis-mybatis-working-with-stored-procedures/

like image 28
nd. Avatar answered Oct 25 '25 11:10

nd.



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!