【问题标题】:How do I stop processing rows in Spring-JDBC?如何停止处理 Spring-JDBC 中的行?
【发布时间】:2018-10-08 03:57:00
【问题描述】:

我有一个消费者可以说他不想处理更多数据。

我查看了 Spring JdbcTemplate 中的方法,但我没有办法通知 Spring 我不想在回调时处理更多行。

我可以抛出一个异常,但是jdbcTemplate.query(...) 会重新抛出这个异常,这是我不希望的行为。

有什么方法可以强制停止处理行而不引起异常?

jdbc.query(sql, new RowCallbackHandler() {

  @Override
  public void processRow(ResultSet rs) throws SQLException
  {
    // TODO how to stop if I want to do it here?
  }}
);

【问题讨论】:

    标签: java spring jdbc spring-jdbc


    【解决方案1】:

    (如果有人来这个线程) - 使用 ResultSetExtractor。 在 while 条件下循环遍历结果集,并在需要时中断。

    Set<String> distinctNames = jdbcTemplate.query(query,
    new ResultSetExtractor<Set<String>>(){
        public Set<String> extractData(ResultSet rs) throws SQLException, DataAccessException {
            Set<String> distinctNames = new HashSet<>();
            Integer cacheMax = 1000
            while(rs.next() && distinctNames.size() <= cacheMax){   
            // magic is in while loop condition to break out when we want ignoring rest of results from DB.
                distinctNames.add(rs.getString("COLUMN_NAME"));
            }
            return distinctNames;
        }
    });
    

    【讨论】:

      【解决方案2】:

      看看:

      jdbcTemplate.setFetchSize(intValue): 向 JDBC 驱动程序提示应该从数据库中获取的行数,当 此语句生成的 ResultSet 对象需要更多行。 如果指定的值为零,则忽略提示。默认 值为零。

      jdbcTemplate.setMaxRows(intValue): 设置此语句生成的任何 ResultSet 对象的最大行数限制 对象可以包含给定的数字。如果超过限制,则 多余的行被静默删除。

      我认为 jdbcTemplate.setMaxRows(intValue) 可能对您的要求有所帮助。

      【讨论】:

      • 之前而不是处理过程中考虑这些参数...
      猜你喜欢
      • 1970-01-01
      • 2011-04-14
      • 1970-01-01
      • 2019-05-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-09-28
      • 1970-01-01
      相关资源
      最近更新 更多