Learn Java for Web Development

(Tina Meador) #1
CHAPTER 1: Introducing Java Web Development 31


  1. } finally {

  2. closeConnection(connection);

  3. }

  4. return result;

  5. }





  6. public List searchBooksByKeyword(String keyWord) {

  7. List result = new ArrayList<>();

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



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



    • " where book_title like '%"





    • keyWord.trim()





    • "%'"





    • " or first_name like '%"





    • keyWord.trim()





    • "%'"





    • " or last_name like '%" + keyWord.trim() + "%'";





  10. Connection connection = null;

  11. try {



  12. connection = getConnection();

  13. PreparedStatement statement = connection.prepareStatement(sql);

  14. ResultSet resultSet = statement.executeQuery();

  15. while (resultSet.next()) {

  16. Book book = new Book();

  17. Author author = new Author();

  18. book.setId(resultSet.getLong("id"));

  19. book.setBookTitle(resultSet.getString("book_title"));

  20. book.setPublisherName(resultSet.getString("publisher"));

  21. author.setFirstName(resultSet.getString("first_name"));

  22. author.setLastName(resultSet.getString("last_name"));

  23. author.setBookId(resultSet.getLong("book_id"));

  24. authorList.add(author);

  25. book.setAuthors(authorList);

  26. result.add(book);

  27. }

  28. } catch (SQLException ex) {

  29. ex.printStackTrace();

  30. } finally {

  31. closeConnection(connection);

  32. }



  33. return result;

  34. }



  35. public List findAllCategories() {

  36. List result = new ArrayList<>();

  37. String sql = "select * from category";



Free download pdf