How do I stop processing rows in Spring-JDBC?
Asked Answered
L

2

6

I have a consumer that can say he doesn't want to process more data.

I've looked upon the methods in Spring JdbcTemplate, but I see no way to inform Spring I don't want to process more rows when I'm on callback.

I could throw an exception, but then the jdbcTemplate.query(...) would rethrow this exception, which is the behavior I don't wish.

Is there any way to force stop processing rows without causing exception?

jdbc.query(sql, new RowCallbackHandler() {

  @Override
  public void processRow(ResultSet rs) throws SQLException
  {
    // TODO how to stop if I want to do it here?
  }}
);
Leftward answered 27/4, 2018 at 10:9 Comment(0)
P
1

(If somebody comes to this thread) - Use ResultSetExtractor. Loop through resultset in while condition and break out when needed.

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;
    }
});
Paint answered 1/7, 2020 at 20:43 Comment(0)
H
0

Take a look into:

jdbcTemplate.setFetchSize(intValue): Gives the JDBC driver a hint as to the number of rows that should be fetched from the database when more rows are needed for ResultSet objects genrated by this Statement. If the value specified is zero, then the hint is ignored. The default value is zero.

jdbcTemplate.setMaxRows(intValue): Sets the limit for the maximum number of rows that any ResultSet object generated by this Statement object can contain to the given number. If the limit is exceeded, the excess rows are silently dropped.

I think that jdbcTemplate.setMaxRows(intValue) could be helpful for your requirements.

Hemocyte answered 27/4, 2018 at 10:22 Comment(1)
Those parameters are taken into account before and not during processing...Leftward

© 2022 - 2024 — McMap. All rights reserved.