简体   繁体   English

使用Java代码启动Oracle存储过程

[英]Launch Oracle stored-procedure in Java code

I wrote a stored-procedure in Oracle and now, I want to launch it in Java code. 我在Oracle中编写了一个存储过程,现在,我想用Java代码启动它。 I will describe a problem. 我将描述一个问题。 I have a object type: 我有一个对象类型:

TYPE PERSON_TYPE AS OBJECT (ID NUMBER(38), NAME VARCHAR2(20));

And table type: 和表类型:

TYPE PERSON_TYPE_TABLE AS TABLE OF PERSON_TYPE;

My procedure looks like this: 我的程序看起来像这样:

PROCEDURE EVALUATE_PERSON_PROC(P_PERSON_ID IN NUMBER, return_data OUT NOCOPY PERSON_TYPE_TABLE) 
AS
--Some code
BEGIN
--Some code
END;

How to launch this procedure in Java code? 如何在Java代码中启动此过程? Which classes are the best to do it? 哪个班级最好?

You need to use the CallableStatement class : 您需要使用CallableStatement类

String sql = "{call EVALUATE_PERSON_PROC(?, ?)}";
CallableStatement statement = connection.prepareCall(sql);
...
statement.execute();

Why not use Spring's DAO abstraction (a very useful and reasonably lightweight library around raw JDBC which eliminates the need for boilerplate code) you can subclass the StoredProcedure class. 为什么不使用Spring的DAO抽象 (一个非常有用且相当轻量级的原始JDBC ,不需要样板代码),你可以StoredProcedure类。

class MySproc extends StoredProcedure {
    public MySproc(DataSource ds) {
       super(" { exec MY_SPROC ?, ? }", ds);
       declare(new SqlParameter("p1", Types.VARCHAR));
       declare(new SqlParameter("p2", Types.INT));
    }

    public void execute(String p1, int p2) {
        Map m = new HashMap();
        m.put("p1", p1);
        m.put("p2", p2);
        super.execute(m);
    }
}

Then this is executed very simply as follows: 然后执行非常简单如下:

new MySproc(ds).execute("Hello", 12);

With no database Connection s, CallableStatement s anywhere to be seen. 没有数据库Connection ,可以在任何地方看到CallableStatement Lovely! 可爱! Oh yes, and it also provides annotation-based Transaction s. 哦,是的,它还提供基于注释的Transaction

If your sproc returns a table, this is incredibly easy using Spring. 如果您的sproc返回一个表,使用Spring非常容易。 Simply declare: 简单声明:

       declare(new SqlReturnResultSet("rs", mapper));

Where mapper is an instance that converts a line of a ResultSet into the desired object. mapper是将ResultSet的一行转换为所需对象的实例。 Then modify your line: 然后修改你的行:

        Map out = super.execute(m);
        return (Collection) out.get("rs");

The returned Collection will contain instances of objects created by your mapper implementation. 返回的Collection将包含mapper实现创建的对象实例。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM