Debug and Fix a Spring Boot Movie Search Across Five Rules
System DesignModel answerLast updated
Repair a broken Spring Boot search endpoint so it handles partial case-insensitive matching, field targeting, popularity ordering, and a published-only filter.
Context
You inherit a Spring Boot backend that exposes a movie search endpoint. The endpoint accepts a search string and a field selector, but it consistently returns wrong results. The logic is spread across three layers — a REST controller, a service class, and a Spring Data JPA repository — and none of the layers has test coverage.
Your job is to diagnose the defects, prove them with tests, and ship a corrected implementation.
The Data Model (given)
A Movie entity has at minimum:
| Field | Type | Notes |
|---|---|---|
id | Long | Primary key |
title | String | The movie title |
stars | Collection<String> | Cast member names |
popularity | double or int | Higher means more popular |
published | boolean | Only true entries are shown |
The Five Rules the Search Must Satisfy
- Substring match — a movie matches when the query string appears anywhere inside the searched field, not only when it equals the whole value.
- Field targeting — the caller specifies whether to match against
title, againststars, or against all fields. - Case-insensitivity — matching must not distinguish upper from lower case in either the query or the stored data.
- Popularity ordering — results are sorted from most popular to least popular; if two movies share the same popularity, a secondary key must break the tie deterministically.
- Published filter — movies with
published = falseare never returned, regardless of field mode.
The endpoint's URL, parameter names, and response shape must not change — existing callers depend on them.
Clarifying Questions You Should Raise
Before writing a single line of code, flag any ambiguity that would affect correctness:
- In all-fields mode, does a movie qualify when the text matches its title or any star, or must it match both?
- Is the popularity sort descending (most popular first)? What is the explicit tie-breaker after popularity?
- What should an empty or absent query return: every published movie, an empty list, or an HTTP 400?
- Is "substring" a plain
LIKE '%x%'match, or should it tolerate word prefixes, diacritics, or typos? - Are results paginated, and can clients override the sort direction?
Part 1 — Write Failing Tests First
Before touching the application code, write tests that pin down each of the five rules. Each test must fail against the current broken implementation and pass after your fix.
For each test describe:
- The test data you would seed
- The input (query string, field mode)
- The expected output (which movies appear, which do not, what order)
- Which layer the test exercises (repository, service, or HTTP) and why you chose that layer
Cover at least one interesting interaction between rules — for example, the published filter combined with a star-field search.
Part 2 — Locate and Name the Defects
Explain how you would trace a request from the controller down to the generated SQL, name the specific bug you would expect to find for each of the five rules, and describe how you would lock in the fix so it cannot silently regress.
Part 3 — Write the Corrected Search
Provide the corrected code for field-choice dispatch, partial case-insensitive matching, the published filter, and the sort order. Decide whether each concern is handled in the database query or in Java, and justify that choice.
Hints
Hint 1
Start with the repository layer: print or log the JPQL/SQL that Spring Data actually generates before assuming the bug is in the service or controller. Hibernate's `show_sql` flag or a `@Query` inspection will save a lot of guessing.
Hint 2
Case-insensitive substring matching in JPQL looks like `LOWER(m.title) LIKE LOWER(CONCAT('%', :q, '%'))`. Doing it in Java instead means loading every row from the database first — avoid that unless the catalog is tiny.
Hint 3
The published filter and the field-choice are two independent boolean conditions; make sure the published check is ANDed with the field match, not ORed. One misplaced parenthesis silently bypasses the filter for one field mode.
Model answer
Hard Try it yourself first — then compare your approach, complexity and edge cases.
Clarifications to Raise First
A strong answer opens with these questions rather than guessing:
- All-fields OR vs AND: Almost certainly OR — a movie qualifies if the text appears in its title or in any star's name. AND would be far too restrictive and would surprise callers.
- Sort direction and tie-breaker: Popularity descending, ties broken by
idascending (ortitleascending). Either works; what matters is that a tie-breaker exists so page boundaries are stable. - Blank query: Return all published movies. An empty LIKE pattern
%%matches everything, which is the least surprising behavior. - Substring definition: Plain
LIKE '%x%', no fuzzy matching, unless the product spec says otherwise.
Part 1 — Failing Tests
Seed three movies before each test:
| title | stars | popularity | published |
|---|---|---|---|
| "The Matrix" | ["Keanu Reeves"] | 90 | true |
| "Speed" | ["Keanu Reeves"] | 70 | true |
| "Draft" | ["Tom Hanks"] | 80 | false |
Test T1 — substring, title mode: query "atri", mode title. Expect ["The Matrix"]. This fails if the repository uses an equality check (=) instead of LIKE.
Test T2 — case-insensitivity, title mode: query "MATRIX", mode title. Expect ["The Matrix"]. This fails if the comparison is case-sensitive.
Test T3 — star mode: query "keanu", mode stars. Expect ["The Matrix", "Speed"] in that order (popularity 90 before 70). This fails if star matching is completely absent or uses equality.
Test T4 — published filter, star mode: query "tom", mode stars. Expect an empty list even though "Draft" has a matching star, because it is unpublished. This is the most important interaction test — it confirms the filter applies in every mode.
Test T5 — all-fields OR: query "speed", mode all. Expect ["Speed"] from title match. Add a sixth movie "Gone" starring "Speeder" (published, popularity 60) and verify it also appears, confirming OR semantics.
Test T6 — popularity order with tie-breaker: add two movies with identical popularity 50 and different id values. Verify the lower id always comes first so the order is deterministic.
Layer rationale: T1–T4 and T6 target the repository layer directly (call the repository method, not the HTTP endpoint) so failures point unambiguously at the query. T5 targets the service layer to verify the field-dispatch logic. One additional integration test through MockMvc covers the controller parsing the field-mode parameter correctly.
Part 2 — Locating the Defects
Tracing strategy: enable spring.jpa.show-sql=true and logging.level.org.hibernate.type=TRACE, then fire a single request and read the printed SQL. This immediately reveals whether the query uses LIKE, whether it lower-cases both sides, and whether the published filter is present. Reading the generated SQL is faster than reading the JPQL because it shows the actual parameter bindings.
Expected defects by rule:
| Rule | Likely defect |
|---|---|
| Substring | Repository uses findByTitleEquals or = instead of LIKE '%…%' |
| Case-insensitivity | Comparison is m.title LIKE :q with no LOWER() on either side |
| Field choice | Service switches on the mode but the stars branch is absent or falls through to title |
| Published filter | Filter is added inside one branch of the switch but omitted from another, or ORed instead of ANDed |
| Ordering | ORDER BY clause missing, or only one key so ties produce non-deterministic pages |
Preventing regression: each failing test from Part 1 is committed before the fix. CI runs the full test suite on every push. The repository queries are @Query-annotated rather than derived method names, so the actual JPQL is visible in source control and reviewed in pull requests.
Part 3 — Corrected Implementation
Decision: push filtering and sorting into the database. Doing it in Java requires loading the entire catalog into memory. With a large catalog that is unacceptable. SQL LOWER() and LIKE are standard and portable across MySQL, PostgreSQL, and H2 (used in tests).
// MovieRepository.java
public interface MovieRepository extends JpaRepository<Movie, Long> {
@Query("""
SELECT DISTINCT m FROM Movie m
JOIN m.stars s
WHERE m.published = true
AND (
LOWER(m.title) LIKE LOWER(CONCAT('%', :q, '%'))
OR LOWER(s) LIKE LOWER(CONCAT('%', :q, '%'))
)
ORDER BY m.popularity DESC, m.id ASC
""")
List<Movie> searchAll(@Param("q") String q);
@Query("""
SELECT m FROM Movie m
WHERE m.published = true
AND LOWER(m.title) LIKE LOWER(CONCAT('%', :q, '%'))
ORDER BY m.popularity DESC, m.id ASC
""")
List<Movie> searchByTitle(@Param("q") String q);
@Query("""
SELECT DISTINCT m FROM Movie m
JOIN m.stars s
WHERE m.published = true
AND LOWER(s) LIKE LOWER(CONCAT('%', :q, '%'))
ORDER BY m.popularity DESC, m.id ASC
""")
List<Movie> searchByStars(@Param("q") String q);
}
// MovieService.java
@Service
public class MovieService {
private final MovieRepository repo;
public MovieService(MovieRepository repo) {
this.repo = repo;
}
public List<Movie> search(String query, String field) {
String q = (query == null) ? "" : query.trim();
return switch (field == null ? "all" : field.toLowerCase()) {
case "title" -> repo.searchByTitle(q);
case "stars" -> repo.searchByStars(q);
default -> repo.searchAll(q);
};
}
}
// MovieController.java (path and params unchanged)
@RestController
@RequestMapping("/movies")
public class MovieController {
private final MovieService service;
public MovieController(MovieService service) {
this.service = service;
}
@GetMapping("/search")
public List<Movie> search(
@RequestParam(defaultValue = "") String query,
@RequestParam(defaultValue = "all") String field) {
return service.search(query, field);
}
}
Key design points:
LOWER()on both the column and the parameter avoids any locale-dependent collation.DISTINCTin the star queries prevents a movie with multiple matching stars appearing twice.published = trueis an AND condition in every branch — it cannot be bypassed by choosing a particular field mode.ORDER BY m.popularity DESC, m.id ASCis explicit and total, so paginated results are stable.- An empty query produces
LIKE '%%'which matches every row — consistent with "return all published movies" semantics.
Cost as the catalog grows: LOWER() on an unindexed column prevents index use and becomes a full table scan. For a large catalog, the fix is a functional index: CREATE INDEX idx_movie_title_lower ON movie (LOWER(title)). For star names stored in a join table, a similar index on the lower-cased star column keeps the query fast. Beyond that, a dedicated search engine (Elasticsearch, OpenSearch) handles substring and fuzzy matching at scale, but that is a separate architectural decision.
Common mistakes to avoid:
- Mixing OR and AND without parentheses so the published filter applies only to some branches.
- Forgetting
DISTINCTand getting duplicate results when a star collection has multiple matches. - Omitting the tie-breaker and then wondering why page 2 sometimes repeats results from page 1.
- Doing the
LOWER()only on the stored value but not on the parameter, soLOWER(m.title) LIKE :qstill fails for an uppercase query.