Java Reference
In-Depth Information
14. import java.apress.books.model.Category;
15.
16. public class BookDAOImpl implements BookDAO {
17.
18. static {
19. try {
20. Class.forName("com.mysql.jdbc.Driver");
21. } catch (ClassNotFoundException ex) {
22. }
23. }
24.
25. private Connection getConnection() throws SQLException {
26. return DriverManager.getConnection("jdbc:mysql://localhost:3306/books",
27. "root", "password");
28. }
29.
30. private void closeConnection(Connection connection) {
31. if (connection == null)
32. return;
33. try {
34. connection.close();
35. } catch (SQLException ex) {
36. }
37. }
38.
39. public List<Book> findAllBooks() {
40. List<Book> result = new ArrayList<>();
41. List<Author> authorList = new ArrayList<>();
42.
43. String sql = "select * from book inner join author on book.id = author.book_id";
44.
45. Connection connection = null;
46. try {
47. connection = getConnection();
48. PreparedStatement statement = connection.prepareStatement(sql);
49. ResultSet resultSet = statement.executeQuery();
50. while (resultSet.next()) {
51. Book book = new Book();
52. Author author = new Author();
53. book.setId(resultSet.getLong("id"));
54. book.setBookTitle(resultSet.getString("book_title"));
55. book.setCategoryId(resultSet.getLong("category_id"));
56. author.setBookId(resultSet.getLong("book_Id"));
57. author.setFirstName(resultSet.getString("first_name"));
58. author.setLastName(resultSet.getString("last_name"));
59. authorList.add(author);
60. book.setAuthors(authorList);
61. book.setPublisherName(resultSet.getString("publisher"));
62. result.add(book);
63. }
64. } catch (SQLException ex) {
65. ex.printStackTrace();
Search WWH ::




Custom Search