Spring-调用具有复杂结果的存储函数



我在PostgreSQL中有以下类型:

CREATE TYPE TR_PERSON AS (
i_out integer,
str_out text
);

此外,我还存储了返回我的类型的函数:

CREATE OR REPLACE FUNCTION test_function(id int)
RETURNS TR_PERSON
AS $$
SELECT $1, text('Alice')
$$ LANGUAGE SQL;

我正在尝试使用spring中的SimpleJdbcCall从DB:中获取数据

SimpleJdbcCall call = new SimpleJdbcCall(jdbcTemplate)
        .withFunctionName("test_function");
SqlParameterSource in = new MapSqlParameterSource().addValue("id", 1);
try {
    TRPerson result = call.executeFunction(TRPerson.class, in);
} catch (DataAccessException e) {
    logger.log(Level.SEVERE, "call failed", e);
}

然后我得到了一个例外:

SEVERE: call failed
org.springframework.dao.InvalidDataAccessApiUsageException: Required input parameter 'i_out' is missing
at org.springframework.jdbc.core.CallableStatementCreatorFactory$CallableStatementCreatorImpl.createCallableStatement(CallableStatementCreatorFactory.java:209)
at org.springframework.jdbc.core.JdbcTemplate.execute(JdbcTemplate.java:1014)
at org.springframework.jdbc.core.JdbcTemplate.call(JdbcTemplate.java:1070)
at org.springframework.jdbc.core.simple.AbstractJdbcCall.executeCallInternal(AbstractJdbcCall.java:387)
at org.springframework.jdbc.core.simple.AbstractJdbcCall.doExecute(AbstractJdbcCall.java:350)
at org.springframework.jdbc.core.simple.SimpleJdbcCall.executeFunction(SimpleJdbcCall.java:154)

我不明白为什么I_out被标记为输入类型。我做错了什么?

SimpleJdbcCall适合我的需求吗?

存储函数和复杂类型结果的最佳实践是什么?

我将非常感谢一些框架代码来捕捉管道。

我找到了解决方案,也许它不理想,但工作良好,在函数返回多条记录的情况下也应该工作(piplined return)。给你。希望它也能帮到你。

String SQL = "select i_out, str_out from test_function1(:id)";
SqlParameterSource namedParameters = new MapSqlParameterSource("id", request.getIntTestVar());
List<TRPerson> result = namedTemplate.query(SQL, namedParameters, new RowMapper() {
    @Override
    public TRPerson mapRow(ResultSet rs, int i) throws SQLException {
        TRPerson result = new TRPerson();
        result.setIntVar(rs.getInt("i_out"));
        result.setStrVar(rs.getString("str_out"));
        return result;
    }
});

最新更新