Thursday, April 14, 2011

Mapping object to row in spring using jdbc template

See this tutorial for getting the feel of spring jdbc template.
The example below uses database and corresponding from this post.
Now we can have our object from result set. Either it can be 1 value returned from select query, or we can have multiple rows. So thats where we have to map the object. Spring provides various ways to map result sets to these objects,eg. Flight.


Querying for Single Row


1. Custom RowMapper


class FlightMapper implements RowMapper<Flight> {
       @Override
    public Flight mapRow(ResultSet rs, int index) throws SQLException {
          Flight flight = new Flight();
          flight.setFlightNo(rs.getString(1));
          flight.setCarrier(rs.getString(2));
          flight.setFrom(rs.getString(3));
          flight.setTo(rs.getString(4));
          return flight;
       }
Now this should be passed to queryForObject function.
Pass it to queryForObject() method, the returned result will call your custom mapRow() method to match the value into the properly.

public Flight getFlightInfo(String flightNo) {
String sql = "select * from flights_test where flightno=?"
        Flight flight = (Flight) jdbcTemplate.queryForObject(sql,new Object[]
                {flightNo}, new FlightMapper());   
        return flight;             
    }


2. BeanPropertyRowMapper

In Spring 2.5, comes with a handy RowMapper implementation called ‘BeanPropertyRowMapper’, which can maps a row’s column value to a property by matching their names. Just make sure both the property and column has the same name, e.g property ‘flightNo’ will match to column name ‘FLIGHTNO’ or with underscores ‘FLIGHT_NO’.
Again queryForObject method can be used.

//Similar to above but using BeanPropertyRowMapper
public Flight getFlightInfo(String flightNo) {
String sql = "select * from flights_test where flightno=?"
        Flight flight = (Flight) jdbcTemplate.queryForObject(sql,new Object[]
                {flightNo}, new BeanPropertyRowMapper(Flight.Class)
());   
        return flight;             
    }

Querying for Multiple Rows

Here’s two examples to show how to query or extract multiple rows from database, and convert it into a List.

1. Map it manually

In mutiple return rows, RowMapper is not supported in query() method, you need to map it manually. 
public List<Flight> getAvailableFlights(String carrier) {
        return jdbcTemplate.query("select * from flights_test where carrier = ?", new FlightMapper(), carrier);
    }

2. BeanPropertyRowMapper

The simplest solution is using the BeanPropertyRowMapper class.
    public List<Flight> getAvailableFlights(String carrier) {
        return jdbcTemplate.query("select * from flights_test where 
        carrier = ?", new BeanPropertyRowMapper(Flight.Class), carrier);
    }





No comments:

Post a Comment

Chitika