我正在使用Springs SimpleJdbcCall
运行存储过程,如下所示:
SimpleJdbcCall jdbcCall = new SimpleJdbcCall(jdbcTemplate).withProcedureName("example_proc");
jdbcCall.execute();
// do other stuff on other subsystems
// the sysout below is just an example - the real scenario was somewhat different
System.out.println("Supposedly after the end of the stored procedure call");
存储过程运行了很长时间,并且与之后发生的事情重叠。
存储过程是用Microsoft的SQL Server方言编写的,看起来像这样:
CREATE PROCEDURE example_proc
AS
BEGIN
INSERT INTO example_table_1 SELECT * FROM example_table_2
UPDATE example_table_1 SET col1 = 'a' WHERE ...
END
问题是:如何确保SimpleJdbcCall
等到存储过程完成?
答案 0 :(得分:0)
对此有一个技巧:使存储过程返回某些内容,然后在jdbc调用中对其进行检索。
这是存储过程:
CREATE PROCEDURE example_proc
AS
BEGIN
INSERT INTO example_table_1 SELECT * FROM example_table_2
UPDATE example_table_1 SET col1 = 'a' WHERE ...
-- this is just a hack for running it synchronously:
SELECT 1 AS success
END
现在它返回了一些内容,jdbc调用可以等待:
SimpleJdbcCall jdbcCall = new SimpleJdbcCall(jdbcTemplate)
.withProcedureName("example_proc").
returningResultSet("success", new SingleColumnRowMapper<Integer>());
Map<String, Object> map = jdbcCall.execute();
@SuppressWarnings("unchecked")
List<Integer> storedProcedureResults = (List<Integer>) map.get(success);
int result = storedProcedureResults.get(0);
// I did something to the result. I am not sure if this is really necessary.
// But I was worried if the jvm or javac would optimize the dead code.
// I returned the value from a method. Printing it should also be enough.
System.out.println(result);