9.3 RowCallbackHandler
RowCallbackHandler is used to process each row of query results rather than collecting them. Unlike RowMapper which returns results, RowCallbackHandler's processRow method returns void,
making it suitable for writing files or sending messages row by row. It does not force the JDBC driver to stream data; configure cursors or fetchSize for large queries. The example below collects names to demonstrate callback output; its memory usage grows with the row count and is not suitable for large-volume consumption.
Interface Definition
@FunctionalInterface
public interface RowCallbackHandler {
void processRow(ResultSet rs, int rowNum) throws SQLException;
}
Custom Implementation Example
public class UserRowCallbackHandler implements RowCallbackHandler {
private final List<String> names = new ArrayList<>();
@Override
public void processRow(ResultSet rs, int rowNum) throws SQLException {
names.add(rs.getString("name"));
}
public List<String> getNames() { return names; }
}
How to Use
Note
RowCallbackHandler uses the query() method (returns void), not queryForList(). Data consumption happens inside processRow.
Example: Programmatic API
UserRowCallbackHandler handler = new UserRowCallbackHandler();
// query() returns void; results are processed inside the handler
jdbc.query("select * from users", handler);
List<String> names = handler.getNames();
Example: Declarative API
@SimpleMapper
public interface UserMapper {
@Query(value = "select * from users where id > #{id}",
resultRowCallback = UserRowCallbackHandler.class)
void listUsers(@Param("id") long searchId);
}
Example: Builder API
UserRowCallbackHandler handler = new UserRowCallbackHandler();
// query() returns void
lambda.query(User.class)
.le(User::getId, 100)
.query(handler);
List<String> names = handler.getNames();
Example: Mapper File
<select id="queryListByAge" resultRowCallback="com.example.dto.UserRowCallbackHandler">
select * from users where age = #{age}
</select>
Built-ins
No built-in implementations. Users can implement the RowCallbackHandler interface based on their needs.