如何从spring JDBC调用表值函数

时间:2013-10-18 06:48:11

标签: spring-jdbc

我想用spring JDBC调用这个语句怎么做

select* from cdc.fn_cdc_get_all_changes_dbo_Student(@from_lsn,@to_lsn,@row_filter_option);

我应该使用JDBCTemplate类还是SimpleJdbcCall类。

我尝试了这个,但它没有奏效:

jdbcTemplate.setResultsMapCaseInsensitive(true);
      SimpleJdbcCall mysimpleJdbcCall = new SimpleJdbcCall(jdbcTemplate);

      mysimpleJdbcCall.withSchemaName("cdc")
                  .withProcedureName("fn_cdc_get_all_changes_dbo_student").returningResultSet("students", 
                            new RowMapper<Student>()
                    {

                      @Override
                      public Student mapRow(ResultSet rs, int rowNum) throws SQLException
                      {
                        Student s = new Student();
                        s.setId(rs.getInt(5));
                        s.setName(rs.getString(6));
                        s.setAge(rs.getInt(7));
                        return s;
                      }
                    });

      MapSqlParameterSource paramSource =new MapSqlParameterSource();
     // paramSource.addValue("capture_instance", "dbo_student");
    paramSource.addValue("from_lsn", lsn1);
    paramSource.addValue("to_lsn", lsn2);
    paramSource.addValue("row_filter_option","all");
    paramSource.addValue("TABLE_RETURN_VALUE", null);
   /* ResultSet rs = mysimpleJdbcCall.executeFunction(ResultSet.class, paramSource);
    return null;*/
    Map m = mysimpleJdbcCall.execute(paramSource);
    List<Student> s=  (List)m.get("students");
    return s;

1 个答案:

答案 0 :(得分:1)

表值函数应该直接调用我们调用查询的方式,而不是通过存储过程方式。

我这样想:

String sql = "select* from cdc.fn_cdc_get_all_changes_" + tableName + "(:from_lsn ,     :tos_lsn , :row_filter_option)";

MapSqlParameterSource params =  new MapSqlParameterSource();
  params.addValue("from_lsn" , lsn1);
params.addValue("tos_lsn", lsn2);
params.addValue("row_filter_option", "all");

List<Student>s = namedParameterJdbcTemplate.query(sql, params, new RowMapper<Student>()
      {

        @Override
        public Student mapRow(ResultSet rs, int rowNo) throws SQLException
        {
          Student s = new Student();
          s.setId(rs.getInt(5));
          s.setName(rs.getString(6));
          s.setAge(rs.getInt(7));
          return s;
        }
      });
return s;