Search This Blog

Friday 7 September 2012

Spring JDBC and SqlQuery

In an earlier post we saw how to use the JdbcTemplate to retrieve multiple rows from the database. There is an alternative way to do the same - using the org.springframework.jdbc.object.SqlQuery class.
public class PersonMapper extends SqlQuery<Person> {

    public static final String QUERY = "select id, name, age from Person";

    @Override
    @SuppressWarnings("rawtypes")
    protected RowMapper<Person> newRowMapper(Object[] paramArrayOfObject, Map paramMap) {

        RowMapper<Person> rowMapper = new RowMapper<Person>() {

            @Override
            public Person mapRow(ResultSet rs, int paramInt)
                    throws SQLException {
                final Person person = new Person();
                person.setId(rs.getLong(1));
                person.setName(rs.getString(2));
                person.setAge(rs.getInt(1));
                return person;
            }
        };
        return rowMapper;
    }

}
The SqlQuery class requires us to implement just the one method.
 The class implements the newRowMapper() method which returns the RowMapper instance. The class  perform the actual work of mapping each row to a result set object. I added the class reference to my DAO implementation:
public class ImprovedPersonDAO implements IPersonDAO {

    private PersonMapper personMapper;

    public List<Person> getAllPersons() {
        return personMapper.execute();
    }
//remaining methods
}
The execute() method is inherited from the SqlQuery class. The bean declaration for the same is as above:
<bean id="improvedPersonDAO" class="com.data.dao.ImprovedPersonDAO">
    <property name="personMapper">
        <bean class="com.data.dao.utility.PersonMapper" >
            <property name ="dataSource" ref="c3pDataSource"/>
            <property name="sql" value="select id, name, age from Person"/>
        </bean>
    </property>
   <!-- remaining properties -->
</bean>
I need not define the class as an inner bean as it is stateless and can very well be shared among multiple threads.
The SqlQuery class is rarely used directly since the MappingSqlQuery subclass provides a much more convenient implementation for mapping rows to Java classes. Other implementations that extend SqlQuery are MappingSqlQueryWithParameters and UpdatableSqlQuery.

No comments:

Post a Comment