首页 Java Java Spring JDBC 调用存储过程(Stored Procedure) 输入(In)输出(Out)参数

Java Spring JDBC 调用存储过程(Stored Procedure) 输入(In)输出(Out)参数

示例存储过程

PROCEDURE MOVE_TO_HISTORY (IN person_id_in INT, OUT status_out BOOLEAN)

1、使用JdbcTemplate#call(CallableStatementCreator csc, List<SqlParameter> inOutParams)调用

public void moveToHistoryTable(Person person) {
List<SqlParameter> parameters = Arrays.asList(
new SqlParameter(Types.BIGINT), new SqlOutParameter("status_out", Types.BOOLEAN));
Map<String, Object> t = jdbcTemplate.call(new CallableStatementCreator() {
@Override
public CallableStatement createCallableStatement(Connection con) throws SQLException {
CallableStatement callableStatement = con.prepareCall("{call MOVE_TO_HISTORY (?, ?)}");
callableStatement.setLong(1, person.getId());
callableStatement.registerOutParameter(2, Types.BOOLEAN);
return callableStatement;
}
}, parameters);
}

2、使用SimpleJdbcCall(这个类大大简化了访问存储过程/函数所需的代码)

public void moveToHistoryTable(Person person){
SimpleJdbcCall call = new SimpleJdbcCall(jdbcTemplate)
.withProcedureName("MOVE_TO_HISTORY")
. declareParameters(
new SqlParameter("peron_id_in", Types.BIGINT),
new SqlOutParameter("status_out", Types.BOOLEAN));
Map<String, Object> execute = call.execute(new MapSqlParameterSource("peron_id_in", person.getId()));
}

3、使用StoredProcedure

该类在包org.springframework.jdbc中。对象,使我们能够以更面向对象的方式访问数据库。StoredProcedure是抽象的,因此我们通常必须扩展它或使用现有的实现。这里我们使用一个子类GenericStoredProcedure

public void moveToHistoryTable(Person person) {
StoredProcedure procedure = new GenericStoredProcedure();
procedure.setDataSource(dataSource);
procedure.setSql("MOVE_TO_HISTORY");
procedure.setFunction(false);
SqlParameter[] parameters = {
new SqlParameter(Types.BIGINT),
new SqlOutParameter("status_out", Types.BOOLEAN)
};
procedure.setParameters(parameters);
procedure.compile();
Map<String, Object> result = procedure.execute(person.getId());
}

参考文档www.logicbig.com/tutorials/spring-framework/spring-data-access-with-jdbc/spring-call-stored-procedur...

特别声明:本站部分内容收集于互联网是出于更直观传递信息的目的。该内容版权归原作者所有,并不代表本站赞同其观点和对其真实性负责。如该内容涉及任何第三方合法权利,请及时与824310991@qq.com联系,我们会及时反馈并处理完毕。