30 CHAPTER 1: Introducing Java Web Development
- import java.apress.books.model.Category;
- public class BookDAOImpl implements BookDAO {
- static {
- try {
- Class.forName("com.mysql.jdbc.Driver");
- } catch (ClassNotFoundException ex) {
- }
- }
- private Connection getConnection() throws SQLException {
- return DriverManager.getConnection("jdbc:mysql://localhost:3306/books",
- "root", "password");
- }
- private void closeConnection(Connection connection) {
- if (connection == null)
- return;
- try {
- connection.close();
- } catch (SQLException ex) {
- }
- }
- public List
findAllBooks() { - List
result = new ArrayList<>(); - List
authorList = new ArrayList<>();
- String sql = "select * from book inner join author on book.id = author.book_id";
- Connection connection = null;
- try {
- connection = getConnection();
- PreparedStatement statement = connection.prepareStatement(sql);
- ResultSet resultSet = statement.executeQuery();
- while (resultSet.next()) {
- Book book = new Book();
- Author author = new Author();
- book.setId(resultSet.getLong("id"));
- book.setBookTitle(resultSet.getString("book_title"));
- book.setCategoryId(resultSet.getLong("category_id"));
- author.setBookId(resultSet.getLong("book_Id"));
- author.setFirstName(resultSet.getString("first_name"));
- author.setLastName(resultSet.getString("last_name"));
- authorList.add(author);
- book.setAuthors(authorList);
- book.setPublisherName(resultSet.getString("publisher"));
- result.add(book);
- }
- } catch (SQLException ex) {
- ex.printStackTrace();