java—如何使用SimpleJDBCall同步调用存储过程

a11xaf1n  于 2021-07-26  发布在  Java
关注(0)|答案(1)|浏览(384)

我在用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 等待存储过程完成?

c7rzv4ha

c7rzv4ha1#

有一种方法可以解决这个问题:让存储过程返回一些东西,然后在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);

相关问题