224 CHAPTER 5: Building Java Web Applications with Spring Web MVC
Compare this findAllBooks() method of BookDAOImpl with the findAllBooks() method of Chapter 1,
and you will see that JDBCTemplate eliminates the boilerplate code that results from using pure JDBC
to obtain a connection to our data store and cleans up resources.
Line 36: This creates a JDBCTemplate using the data source passed to it.
Note the JDBCTemplate is instantiated this way for the sake of explanation. In a
production ready application you should inject JDBCTemplate as a dependency
like any other dependency as explained in Listing 5-15.
Line 37: A row mapper implementation is used. The BookRowMapper is explained next.
Listing 5-27 illustrates the BookRowMapper object to query one or more rows and then transform each
row into the corresponding domain object instead of retrieving a single value.
Listing 5-27. The BookMapper Object
- package com.apress.books.dao;
- import java.sql.ResultSet;
- import java.sql.SQLException;
- import org.springframework.jdbc.core.RowMapper;
- import com.apress.books.model.Book;
- public class BookRowMapper implements RowMapper
{
- @Override
- public Book mapRow(ResultSet resultSet, int line) throws SQLException {
- BookExtractor bookExtractor = new BookExtractor();
- return bookExtractor.extractData(resultSet);
- }
- }
Line 10: Spring’s RowMapper<T> interface (under the package
org.springframework.jdbc.core) provides a simple way for you to perform
mapping from a JDBC resultset to POJOs.
Line 14: This uses BookExtractor to extract the data.
Listing 5-28 illustrates the BookExtractor object.
Listing 5-28. BookExtractor Object
- package com.apress.books.dao;
- import java.sql.ResultSet;
- import java.sql.SQLException;
- import java.util.ArrayList;
- import java.util.List;