图书搜索系统
CityBook Libraries 目前的搜索仅支持精确书名。他们需要一个更灵活的搜索功能,允许访客按部分书名、作者名,或两者的任意组合进行搜索。
您将创建一个动态查询构建器,根据用户提供的搜索条件构造 SQL 查询。HikariSetup 类已为您配置好。
本练习是课程的一部分
在 Java 中查询 PostgreSQL 数据库
练习说明
- 将书名条件追加到查询中。
- 如果已经添加了书名条件,则在查询中添加 AND;否则添加 WHERE。
- 完成查询,使其按书名排序。
交互式实操练习
通过完成这段示例代码来试试这个练习。
public class Main {
public static void main(String[] args) {
String titleSearch = "first";
String authorSearch = null;
StringBuilder sql = new StringBuilder(
"SELECT b.title, a.first_name AS author " +
"FROM books b " +
"JOIN book_authors ba ON b.book_id = ba.book_id " +
"JOIN authors a ON ba.author_id = a.author_id ");
boolean hasTitleSearch = false;
if (titleSearch != null && !titleSearch.isEmpty()) {
// Append the title condition
sql.____("WHERE b.title ILIKE ? ");
hasTitleSearch = true;
}
if (authorSearch != null && !authorSearch.isEmpty()) {
// Add AND if you added title condition or WHERE if not
sql.append(hasTitleSearch ? "AND " : "____");
sql.append(" a.first_name ILIKE ? ");
}
// Complete the query to sort by title
sql.append("____ ____ b.title");
System.out.println(sql);
}
}