您的位置:首页 > 数据库 > Oracle

How to call Oracle function or stored procedure using spring persistence framework?

2012-11-22 16:52 991 查看
Assuming you are referring to JdbcTemplate:

jdbcTemplate.execute(
new CallableStatementCreator() {
public CallableStatement createCallableStatement(Connection con) throws SQLException{
CallableStatement cs = con.prepareCall("{call MY_STORED_PROCEDURE(?, ?, ?)}");
cs.setInt(1, ...); // first argument
cs.setInt(2, ...); // second argument
cs.setInt(3, ...); // third argument
return cs;
}
},
new CallableStatementCallback() {
public Object doInCallableStatement(CallableStatement cs) throws SQLException{
cs.execute();
return null; // Whatever is returned here is returned from the jdbcTemplate.execute method
}
}
);


Calling a function is almost identical:

jdbcTemplate.execute(
new CallableStatementCreator() {
public CallableStatement createCallableStatement(Connection con) {
CallableStatement cs = con.prepareCall("{? = call MY_FUNCTION(?, ?, ?)}");
cs.registerOutParameter(1, Types.INTEGER); // or whatever type your function returns.
// Set your arguments
cs.setInt(2, ...); // first argument
cs.setInt(3, ...); // second argument
cs.setInt(4, ...); // third argument
return cs;
}
},
new CallableStatementCallback {
public Object doInCallableStatement(CallableStatement cs) {
cs.execute();
int result = cs.getInt(1);
return result; // Whatever is returned here is returned from the jdbcTemplate.execute method
}
}
);


There are a number of ways to call stored procedures in Spring.

If you use CallableStatementCreator to declare parameters, you will be using Java's standard interface of CallableStatement, i.e register out parameters and set them separately. Using SqlParameter abstraction will make your code cleaner.

I recommend you looking at SimpleJdbcCall. It may be used like this:

SimpleJdbcCall jdbcCall = new SimpleJdbcCall(jdbcTemplate)
.withSchemaName(schema)
.withCatalogName(package)
.withProcedureName(procedure)();
...
jdbcCall.addDeclaredParameter(new SqlParameter(paramName, OracleTypes.NUMBER));
...
jdbcCall.execute(callParams);
For simple procedures you may use jdbcTemplate's update method:

jdbcTemplate.update("call SOME_PROC (?, ?)", param1, param2);


转载地址:http://stackoverflow.com/questions/862694/how-to-call-oracle-function-or-stored-procedure-using-spring-persistence-framewo
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: