tl  tr
  Home | Tutorials | Articles | Videos | Products | Tools | Search
Interviews | Open Source | Tag Cloud | Follow Us | Bookmark | Contact   
 Spring > JDBC > Row Callback Handler

Row Callback Handler 

Spring JDBC Framework simplifies the use of JDBC and helps to avoid common errors. The following example shows using RowCallbackHandler interface. This callback interface is called once for processing each row. The CustomRowCallbackHandler given in this examples buffers the user names from each row.


File Name  :  
/SpringJDBC001/conf/basic/applicationContext.xml 

File Name  :  
com/bethecoder/tutorials/spring3/tests/RowCallbackHandlerTest.java 
Author  :  Sudhakar KV
Email  :  [email protected]
   
package com.bethecoder.tutorials.spring3.tests;

import java.sql.ResultSet;
import java.sql.SQLException;

import javax.sql.DataSource;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowCallbackHandler;

public class RowCallbackHandlerTest {

  /**
   @param args
   */
  public static void main(String[] args) {
    
    /**
     * Initialize context and get the JdbcTemplate
     */
    ApplicationContext appContext = new ClassPathXmlApplicationContext("applicationContext.xml");
    DataSource dataSource = (DataSourceappContext.getBean("dataSource");
    JdbcTemplate template = new JdbcTemplate(dataSource);

    CustomRowCallbackHandler handler = new CustomRowCallbackHandler();
    template.query("select * from USER", handler);
    System.out.println("Names : " + handler.getUserNames());
  }

}
//RowCallbackHandler is stateful
class CustomRowCallbackHandler implements RowCallbackHandler {
  
  private StringBuilder sb = new StringBuilder();
  
  @Override
  public void processRow(ResultSet rsthrows SQLException {
    if (sb.length() != 0) {
      sb.append(", ");
    }
    
    sb.append(rs.getString("NAME"));
  }
  
  public String getUserNames() {
    return sb.toString();
  }
}
   

It gives the following output,
Names : Sriram, Anu, Sudhakar, Charan, Bunny



 
  


  
bl  br