[英]How to call a stored procedure with ref cursor as an output parameter using Spring?
我有一个存储过程,其主体如下:-
PROCEDURE PROC_NAME(param1 in varchar2,param2 in varchar2,results_cursor OUT CURSOR_TYPE);
结果的每一行等效于某个用户定义类的实例。
在春季如何称呼它。 我经历了很多谷歌和stackoverflow,但找不到合适的答案。
谁能为我提供解决方案。 提前致谢。
这是我根据StackOverflow问题和Spring文档整理而成的 :
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")
请看一下。 列出userData;
SimpleJdbcCall executor = new SimpleJdbcCall(jdbcTemplate)
.withProcedureName("SP_CL_USERPKS_FOLDER").withoutProcedureColumnMetaDataAccess()
.declareParameters(
new SqlParameter("INparam1", Types.INTEGER),
new SqlParameter("INparam2", Types.VARCHAR),
new SqlOutParameter("OUTParam1", OracleTypes.CURSOR),
new SqlOutParameter("OUTParam2", OracleTypes.VARCHAR));
executor.compile();
SqlParameterSource param = new MapSqlParameterSource()
.addValue("INparam1", loginPk)
.addValue("INparam2", email);
Map map = executor.execute(param);
userData = (List<Map>) map.get("OUTParam1");
String msg = (String) map.get("OUTParam2");
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.