Wednesday, July 13, 2011

ResultSetExtractor in Spring


Create the entry in the database:
For this we will take flight database and flight entity as our pojo class.
See - Create flights in database and corresponding pojo class

Now using the ResultSetExtractor
First we will implement result set extractor
public class FlightResultSetExtractor implements ResultSetExtractor<List<Flight>> {

   @Override
   public Object extractData(ResultSet rs) throws SQLException {
      List<Flight> flightList = new ArrayList<Flight>();      
      while(rs.next){
         Flight flight = new Flight();
         flight.setFlightNo(rs.getString(1));
         flight.setCarrierName(rs.getString(2));
         flightList.add(flight);
      }
      return list;
  }
}

Now using the ResultSetExtractor
Initialize JdbcTemplate as jdbcTemplate first
public List<Flight> getAllTodaysFlight(){
   String sql = "Get all flights where date=?";
   Date today = getTodaysDate();
   Object[] args = {date};
   FlightResultSetExtractor extractor = new FlightResultSetExtractor();
   return jdbcTemplate.query(src, args, extractor);
}

No comments:

Post a Comment

Chitika