我有一个存储过程,其主体如下:-
PROCEDURE PROC_NAME(varchar2 中的参数 1,varchar2 中的参数2,results_cursor OUT CURSOR_TYPE);
每一行结果相当于某个用户定义类的实例。
如何在 Spring 中调用它?我查了很多谷歌和 stackoverflow 但找不到合适的答案。
任何人都可以为我提供解决方案吗?提前致谢。
最佳答案
这是我根据 this StackOverflow question 整理的内容和 the 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")
关于java - 如何使用 Spring 调用以引用游标作为输出参数的存储过程?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43045032/