Spring - 调用存储函数,结果复杂

时间:2013-12-12 07:50:32

标签: java spring postgresql spring-jdbc complextype

我在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是否适合我的需求?

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

我非常感谢一些骨架代码来捕获管道。

1 个答案:

答案 0 :(得分:2)

我找到了解决方案,也许它不理想,但运行良好,也应该工作以防多个记录从函数返回(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;
    }
});