도서 검색 시스템
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);
}
}