部分应用通过存储过程和函数来处理相关业务逻辑,以达到跨应用共享的目的,因此调用存储过程就成了Java程序员不得不面对的一个问题。Java的JDBC就可以实现该需求,而Spring的JdbcTemplate是对JDBC的封装,因此也是可以实现调用存储过程和函数的。下列代码分别时调用存储过程和函数的示例。
示例1:无参数和无返回值的存储过程调用。
public void callProcedureWithouParamAndResult() {
jdbcTemplate.execute("{ call procedure_name() }")
}
示例2:有入参和出参的存储过程调用。
public void callProcedureWithParamAndResult() {
String result = (String)jdbcTemplate.execute(new CallableStatementCreate() {
public CallableStatement createCallableStatement(Connection connection) throws SQLException {
// 假设存储过程procedure_name第一个参数为入参,第二个参数为出参
CallableStatement cs = connection.prepareCall("{ call procedure_name(?, ?)}");
cs.setString(1, "param");
cs.registerOutParameter(2, OracleTypes.NVARCHAR);
return cs;
}
}, new CallableStatementCallback<Object>() {
public Object doInCallableStatement(CallableStatement cs) throws SQLException, DataAccessException {
cs.execute();
return cs.getString(2);// 获取输出参数的值
}
});
System.out.println(result);
}
示例3:无参数的函数调用。
public void callProcedureWithParamAndResult() {
String result = (String)jdbcTemplate.execute(new CallableStatementCreate() {
public CallableStatement createCallableStatement(Connection connection) throws SQLException {
// 假设函数function_name无入参,有返回值
CallableStatement cs = connection.prepareCall("{ ? = call function_name()}");
cs.registerOutParameter(1, OracleTypes.NVARCHAR);
return cs;
}
}, new CallableStatementCallback<Object>() {
public Object doInCallableStatement(CallableStatement cs) throws SQLException, DataAccessException {
cs.execute();
return cs.getString(1);// 获取输出参数的值
}
});
System.out.println(result);
}
示例4:有入参、出参和返回值的函数调用。
public void callProcedureWithParamAndResult() {
String result = (String)jdbcTemplate.execute(new CallableStatementCreate() {
public CallableStatement createCallableStatement(Connection connection) throws SQLException {
// 假设函数function_name第一个参数为入参,第二个参数为出参,并且有返回值
CallableStatement cs = connection.prepareCall("{ ? = call function_name(?, ?)}");
cs.registerOutParameter(1, OracleTypes.NVARCHAR);
cs.setString(2, "param");
cs.registerOutParameter(2, OracleTypes.NVARCHAR);
return cs;
}
}, new CallableStatementCallback<Object>() {
public Object doInCallableStatement(CallableStatement cs) throws SQLException, DataAccessException {
cs.execute();
return cs.getString(3);// 获取输出参数的值
}
});
System.out.println(result);
}