這裏的東西我放在一起基於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")
我不知道如何使用JdbcTemplate完成此操作,但我使用普通JDBC完成了此操作。如果您可以使用JDBC,我可以發佈一些代碼。 –
@dsp_user:我無法在我的代碼中使用JDBC。 –
那麼,JDBCTemplate已經在內部使用它,但這真的取決於你。 –