2011-05-18 62 views
3

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

如果我使用 jdbcTemplate.queryForList(myStoredProc, new Object[]{parameters} iam从结果中只获得第一个表。

我的数据库是SQL Server 2005中

是否有我的要求比其他的JdbcTemplate任何方法。如果是的话,请让我知道。

在此先感谢....

回答

4

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

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

+1

非常不错的链接。谢了哥们。 – Krishna 2011-05-18 09:33:04

+0

我是uwing spring的StoredProc,返回标量或只有一行的proc结果,但我很好奇如何处理这种情况。你知道在返回multipe行的proc的情况下返回的Map的内容是什么?它是地图的地图,其中封闭的地图键是行索引吗? – Guillaume 2012-05-16 16:56:23

8

引用的解决方案并不适合我。我能用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; 
} 
+0

谢谢! 'SqlReturnResultSet'就是我一直在寻找的东西。 :) – 2015-09-03 11:30:42