Learn Java for Web Development

(Tina Meador) #1

30 CHAPTER 1: Introducing Java Web Development



  1. import java.apress.books.model.Category;



  2. public class BookDAOImpl implements BookDAO {



  3. static {

  4. try {

  5. Class.forName("com.mysql.jdbc.Driver");

  6. } catch (ClassNotFoundException ex) {

  7. }

  8. }



  9. private Connection getConnection() throws SQLException {

  10. return DriverManager.getConnection("jdbc:mysql://localhost:3306/books",

  11. "root", "password");

  12. }



  13. private void closeConnection(Connection connection) {

  14. if (connection == null)

  15. return;

  16. try {

  17. connection.close();

  18. } catch (SQLException ex) {

  19. }

  20. }



  21. public List findAllBooks() {

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

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



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



  25. Connection connection = null;

  26. try {

  27. connection = getConnection();

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

  29. ResultSet resultSet = statement.executeQuery();

  30. while (resultSet.next()) {

  31. Book book = new Book();

  32. Author author = new Author();

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

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

  35. book.setCategoryId(resultSet.getLong("category_id"));

  36. author.setBookId(resultSet.getLong("book_Id"));

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

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

  39. authorList.add(author);

  40. book.setAuthors(authorList);

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

  42. result.add(book);

  43. }

  44. } catch (SQLException ex) {

  45. ex.printStackTrace();

Free download pdf