[英]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.