public class DatabaseConfig { private static final String JDBC_URL = "jdbc:mysql://localhost:3306/library"; private static final String USERNAME = "root"; private static final String PASSWORD = "password"; public static Connection getConnection() { Connection connection = null; try { connection = DriverManager.getConnection(JDBC_URL, USERNAME, PASSWORD); } catch (SQLException e) { e.printStackTrace(); } return connection; } } public class BookDao { public List<Book> getAllBooks() { List<Book> books = new ArrayList<>(); Connection connection = DatabaseConfig.getConnection(); Statement statement = null; ResultSet resultSet = null; try { statement = connection.createStatement(); resultSet = statement.executeQuery("SELECT * FROM books"); while (resultSet.next()) { int id = resultSet.getInt("id"); String title = resultSet.getString("title"); String author = resultSet.getString("author"); float price = resultSet.getFloat("price"); books.add(new Book(id, title, author, price)); } } catch (SQLException e) { e.printStackTrace(); } finally { try { resultSet.close(); statement.close(); connection.close(); } catch (SQLException e) { e.printStackTrace(); } } return books; } } public class BookCache { private static final Map<String, List<Book>> cache = new ConcurrentHashMap<>(); public List<Book> getBooksByCategory(String category) { if (cache.containsKey(category)) { return cache.get(category); } else { List<Book> books = BookDao.getAllBooksByCategory(category); cache.put(category, books); return books; } } } public class Main { public static void main(String[] args) { BookCache cache = new BookCache(); List<Book> books = cache.getBooksByCategory("Science"); for (Book book : books) { System.out.println(book.getTitle() + " - " + book.getAuthor()); } } }


上一篇:
下一篇:
切换中文