Learn Java for Web Development

(Tina Meador) #1
CHAPTER 5: Building Java Web Applications with Spring Web MVC 225


  1. import org.springframework.dao.DataAccessException;

  2. import org.springframework.jdbc.core.ResultSetExtractor;



  3. import com.apress.books.model.Author;

  4. import com.apress.books.model.Book;



  5. public class BookExtractor implements ResultSetExtractor {



  6. public Book extractData(ResultSet resultSet) throws SQLException,

  7. DataAccessException {



  8. Book book = new Book();

  9. Author author = new Author();

  10. List authorList = new ArrayList<>();



  11. book.setId(resultSet.getLong(1));

  12. book.setCategoryId(resultSet.getLong(2));

  13. book.setBookTitle(resultSet.getString(3));

  14. book.setPublisherName(resultSet.getString(4));

  15. book.setAuthorId(resultSet.getLong(5));

  16. author.setBookId(resultSet.getLong(6));

  17. author.setFirstName(resultSet.getString(7));

  18. author.setLastName(resultSet.getString(8));

  19. authorList.add(author);

  20. book.setAuthors(authorList);



  21. return book;

  22. }



  23. }


   Line 14: BookExtractor implements ResultSetExtractor provided by Spring
(under the package org.springframework.jdbc.core). The RowMapper is suitable
only for mapping to a single domain object. But since we are joining two tables
in Listing 5-26 on line 34, we need to use the ResultSetExtractor interface to
transform the data to a nested domain object.

Listing 5-29 illustrates the configuration file for this stand-alone application.


Listing 5-29. Configuration File



  1. <?xml version="1.0" encoding="UTF-8"?>

  2. <beans xmlns="http://www.springframework.org/schema/beans"

  3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context=
    "http://www.springframework.org/schema/context"

  4. xmlns:aop="http://www.springframework.org/schema/aop"

  5. xsi:schemaLocation="http://www.springframework.org/schema/beans

  6. http://www.springframework.org/schema/beans/spring-beans-3.2.xsd

  7. http://www.springframework.org/schema/context

  8. http://www.springframework.org/schema/context/spring-context-3.2.xsd

  9. http://www.springframework.org/schema/aop

  10. http://www.springframework.org/schema/aop/spring-aop-3.2.xsd">



Free download pdf