存储过程将多个表返回到spring jdbc模板

时间:2011-05-18 05:47:05

标签: java stored-procedures spring-mvc spring-jdbc

Iam使用JdbcTemplate从我的Spring DAO类调用存储过程。我的问题是,存储过程返回多个表。有没有办法使用Spring JdbcTemplate访问多个表。

如果我使用  jdbcTemplate.queryForList(myStoredProc, new Object[]{parameters} 我只从结果中得到第一张桌子。

我的数据库是SQL Server 2005。

我的要求是否有除jdbcTemplate之外的任何方法。如果是,请告诉我。

提前致谢....

2 个答案:

答案 0 :(得分:9)

引用sinha的解决方案对我不起作用。我能够使用JdbcTemplate#call(CallableStatementCreator, List<SqlParameter>)来解决这个问题。例如:

private static final String sql = "{call schema_name.the_stored_procedure(?, ?, ?)}";

// The input parameters of the stored procedure
private static final List<SqlParameter> declaredParams = Arrays.asList(
    new SqlParameter("nameOfFirstInputParam", Types.VARCHAR),
    new SqlParameter("nameOfSecondInputParam", Types.VARCHAR),
    new SqlParameter("nameOfThirdInputParam", Types.VARCHAR));

private static final CallableStatementCreatorFactory cscFactory
    = new CallableStatementCreatorFactory(sql, declaredParams);

// The result sets of the stored procedure
private static final List<SqlParameter> returnedParams = Arrays.<SqlParameter>asList(
    new SqlReturnResultSet("nameOfFirstResultSet", SomeRowMapper.INSTANCE),
    new SqlReturnResultSet("nameOfSecondResultSet", SomeOtherRowMapper.INSTANCE));

public static Map<String, Object> call(JdbcTemplate jdbcTemplate,
                                       String param0,
                                       String param1,
                                       String param2) {
  final Map<String, Object> actualParams = new HashMap<>();
  actualParams.put("nameOfFirstInputParam", param0);
  actualParams.put("nameOfSecondInputParam", param1);
  actualParams.put("nameOfThirdInputParam", param2);

  CallableStatementCreator csc = cscFactory.newCallableStatementCreator(actualParams);
  Map<String, Object> results = jdbcTemplate.call(csc, returnedParams);

  // The returned map will including a mapping for each result set.
  //
  // {
  //   "nameOfFirstResultSet" -> List<SomeObject>
  //   "nameOfSecondResultSet" -> List<SomeOtherObject>
  // }
  //
  // For this example, we just return the heterogeneous map.  In practice,
  // it's better to return an object with more type information.  In other
  // words, don't make client code cast the result set lists.  Encapsulate
  // that casting within this method.

  return results;
}

答案 1 :(得分:4)

请参阅http://static.springsource.org/spring/docs/2.0.7/reference/jdbc.html#jdbc-StoredProcedure

本节中给出的示例完全适用于存储过程返回多个结果集的情况。虽然给出的示例适用于Oracle,但它也应该以相同的方式为MS SQL Server工作。