问题
I am attempting to execute a stored procedure from Spring Batch, the stored procedure has two parameters, an IN parameter and OUT parameter. What I want is to get the result set and the out parameter when the stored procedure is called.
I referred to StoredProcedureItemReader and StoredProcedureItemReaderBuilder
I can use this to call a stored procedure that has only IN parameter, however, I can't call after registering OUT parameter.
If we refer raw JDBC template we could use, it is possible to call a Store Procedure with IN and OUT variables using https://docs.oracle.com/javase/7/docs/api/java/sql/CallableStatement.html
And I believe that StoredProcedureItemReader
or StoredProcedureIteamReaderBuilder
uses CallableStatement
behind the scenes.
My question is, how do I register OUT parameters to execute within Spring Batch using StoredProcedureItemReaderBuilder
Here's a sample code I tried
@StepScope
@Bean
public StoredProcedureItemReader<MyRow> rowReader(@Value("#{stepExecutionContext[tableName]}") String tableName) {
return new StoredProcedureItemReaderBuilder<MyRow>()
.procedureName("GetNameCountByFname")
.parameters(
new SqlParameter[]{
new SqlParameter("fname", Types.VARCHAR),
new SqlOutParameter("total", Types.INTEGER)
}).
preparedStatementSetter(
new PreparedStatementSetter() {
@Override
public void setValues(PreparedStatement ps)
throws SQLException {
ps.setString(1, "bob");
}
}
.rowMapper(new MyRowMapper(tableName))
.name(tableName + "_read")
.dataSource(dataSource)
.build();
}
The following error is given:
Caused by: java.lang.ArrayIndexOutOfBoundsException: -1
at java.util.ArrayList.elementData(ArrayList.java:422) ~[na:1.8.0_251]
at java.util.ArrayList.get(ArrayList.java:435) ~[na:1.8.0_251]
at com.mysql.cj.jdbc.CallableStatement$CallableStatementParamInfo.getParameter(CallableStatement.java:283) ~[mysql-connector-java-8.0.20.jar:8.0.20]
at com.mysql.cj.jdbc.CallableStatement.checkIsOutputParam(CallableStatement.java:634) ~[mysql-connector-java-8.0.20.jar:8.0.20]
at com.mysql.cj.jdbc.CallableStatement.getObject(CallableStatement.java:1356) ~[mysql-connector-java-8.0.20.jar:8.0.20]
The following stored procedure is called
DELIMITER $$
CREATE PROCEDURE GetNameCountByFname(
IN fname VARCHAR(25),
OUT total INT
)
BEGIN
SELECT COUNT(*)
INTO total
FROM `first`
WHERE `name` = fname;
END$$
DELIMITER ;
回答1:
My question is, how do I register OUT parameters to execute within Spring Batch using StoredProcedureItemReaderBuilder
That's not possible. This feature has been already requested but was rejected. Please find more details in https://github.com/spring-projects/spring-batch/issues/2024.
来源:https://stackoverflow.com/questions/62187086/calling-stored-procedure-with-an-in-and-out-parameter-from-spring-batch