2017-03-27 147 views
0

我有一个存储过程,其具有体,如: -如何使用Spring将ref cursor作为输出参数调用存储过程?

PROCEDURE PROC_NAME(param1 in varchar2,param2 in varchar2,results_cursor OUT CURSOR_TYPE);

结果中的每个行是等同于某一用户定义的类的实例。

如何在Spring中调用此方法。我经历了很多谷歌和stackoverflow,但无法找到一个合适的答案。

任何人都可以请给我一个解决方案。提前致谢。

+0

我不知道如何使用JdbcTemplate完成此操作,但我使用普通JDBC完成了此操作。如果您可以使用JDBC,我可以发布一些代码。 –

+0

@dsp_user:我无法在我的代码中使用JDBC。 –

+0

那么,JDBCTemplate已经在内部使用它,但这真的取决于你。 –

回答

1

这里的东西我放在一起基于this StackOverflow questionthe Spring documentation

import java.sql.Types; 
import java.util.HashMap; 
import java.util.Map; 

import javax.sql.DataSource; 

import oracle.jdbc.OracleTypes; 
import org.springframework.jdbc.core.SqlOutParameter; 
import org.springframework.jdbc.core.SqlParameter; 
import org.springframework.jdbc.object.StoredProcedure; 

public class SampleStoredProcedure extends StoredProcedure { 

    public SampleStoredProcedure(DataSource dataSource) { 
     super(dataSource, "PROC_NAME"); 
     declareParameter(new SqlParameter("param1", Types.VARCHAR)); 
     declareParameter(new SqlParameter("param2", Types.VARCHAR)); 
     declareParameter(new SqlOutParameter("results_cursor", OracleTypes.CURSOR, new SomeRowMapper())); 
     compile(); 
    } 

    public Map<String, Object> execute(String param1, String param2) { 
     Map<String, Object> inParams = new HashMap<>(); 
     inParams.put("param1", param1); 
     inParams.put("param2", param2); 
     Map output = execute(inParams); 
     return output; 
    } 
} 

如果你的存储过程是另一种模式或在包中,你需要在上述调整存储过程的名称。此外,您需要指定一个行映射器来代替SomeRowMapper。另外

DataSource dataSource = ... ; // get this from somewhere 
    SampleStoredProcedure sp = new SampleStoredProcedure(dataSource); 
    Map<String, Object> result = sp.execute("some string", "some other string"); 
    // Do something with 'result': in particular, result.get("results_cursor") 
    // will be the list of objects returned 

,你可以使用一个SimpleJdbcCall

要叫它

DataSource dataSource = ... ; // get this from somewhere 
    SimpleJdbcCall jdbcCall = new SimpleJdbcCall(dataSource); 
    Map<String, Object> result = 
     jdbcCall.withProcedureName("PROC_NAME") 
      .declareParameters(
        new SqlParameter("param1", Types.VARCHAR), 
        new SqlParameter("param2", Types.VARCHAR), 
        new SqlOutParameter("results_cursor", OracleTypes.CURSOR, new SomeRowMapper())) 
      .execute("some string", "some other string"); 

如果存储过程是在一个包,你需要添加一行

  .withCatalogName("PACKAGE_NAME") 

到设置jdbcCall。同样,如果它在不同的架构中,则需要添加

  .withSchemaName("SCHEMA_NAME") 
相关问题