Learn Java for Web Development

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

public interface BookDAO {
public List findAllBooks();


}


Listing 5-26 illustrates the BookDAO implementation.


Listing 5-26. BookDAO Implementation



  1. package com.apress.books.dao;



  2. import java.sql.Connection;

  3. import java.sql.DriverManager;

  4. import java.sql.PreparedStatement;

  5. import java.sql.ResultSet;

  6. import java.sql.SQLException;

  7. import java.sql.Statement;

  8. import java.util.ArrayList;

  9. import java.util.List;



  10. import javax.sql.DataSource;



  11. import org.springframework.beans.factory.annotation.Autowired;

  12. import org.springframework.jdbc.core.JdbcTemplate;



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

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

  15. import com.apress.books.model.Category;



  16. public class BookDAOImpl implements BookDAO {





  17. DataSource dataSource;





  18. public void setDataSource(DataSource dataSource) {

  19. this.dataSource = dataSource;

  20. }



  21. public List findAllBooks() {

  22. List bookList = new ArrayList<>();



  23. String sql = "select * from book inner join author on book.id = author.book_id";



  24. JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);

  25. bookList = jdbcTemplate.query(sql, new BookRowMapper());

  26. return bookList;

  27. }



  28. }

Free download pdf