Hint
This article is generated by AI translation.
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 streaming large-scale data (such as writing to files row by row, sending messages, etc.) without data accumulating in memory.
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: Fluent 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.