Implementing RowCallbackHandler

Spring provides a simpler RowCallbackHandler interface when there is no return object. It is used to stream rows to a file, converting the rows to XML, and filtering them before adding to a collection. But filtering in SQL is much more efficient, and is faster than the JPA equivalent for big queries. Let's look at the following example:

    public interface RowCallbackHandler { 
      void processRow(ResultSet rs) throws SQLException; 
    } 

 

Example for using a RowCallbackHandler

The following code is an example of a RowCallbackHandler in the application:

    package com.packt.patterninspring.chapter7.bankapp.callbacks; 
    import java.sql.ResultSet; 
    import java.sql.SQLException; 
    import org.springframework.jdbc.core.RowCallbackHandler; 
    public class AccountReportWriter implements RowCallbackHandler { 
      public void processRow(ResultSet resultSet) throws SQLException { 
        // parse current row from ResultSet and stream to output 
        //write flat file, XML 
      } 
    } 

In preceding code, we have created a RowCallbackHandler implementation; the AccountReportWriter class implements this interface to process the result set returned from the database. Let's see the following code how to use AccountReportWriter call back class:

    @Override 
    public void generateReport(Writer out, String branchName) { 
      String sql = "SELECT * FROM Account WHERE branchName = "+
branchName; jdbcTemplate.query(sql, new AccountReportWriter()); }

RowCallbackHandler is the best choice when no value should be returned from the callback method for each row, especially for large queries.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset