Quick revision
The short answer
We first find out which queries are really used, combining code search with runtime evidence from Hibernate statistics or pg_stat_statements. Used queries move next to their repository methods as @Query, or into orm.xml, so entities stay lean. Near-duplicates are merged only when tests prove they return the same rows in the same order with the same null handling, startup validation catches typos while repository tests on a real database check behaviour, and dead queries are removed in small changes so any rollback is easy.
What to remember
In this answer, we cleaned up 300 named queries safely. We collected usage evidence from code search, Hibernate statistics and pg_stat_statements, moved live queries next to their repository methods with @Query or into orm.xml, merged near-duplicates only after tests on a real database proved equal results including ordering and nulls, relied on startup validation for typos and repository tests for behaviour, and removed dead queries in small, easily reverted changes.
Your turn
Answer it aloud as you would in the interview, or type your answer below. Then show one part at a time and compare.
We first find out which queries are really used, combining code search with runtime evidence from Hibernate statistics or pg_stat_statements. Used queries move next to their repository methods as @Query, or into orm.xml, so entities stay lean. Near-duplicates are merged only when tests prove they return the same rows in the same order with the same null handling, startup validation catches typos while repository tests on a real database check behaviour, and dead queries are removed in small changes so any rollback is easy.
Why this question is asked
Three hundred named queries spread over entity classes is a common sight in modules that grew for a decade. Entities become hard to read, nobody knows which queries matter, and copies like Order.findOpen and Order.findOpenOrders differ in a detail nobody remembers choosing. Interviewers ask this scenario to see whether we can clean up without breaking production, which is mostly about evidence and small steps. In this answer, we will see why named queries are hard to trace, gather usage evidence, decide where the live ones should go, merge near-duplicates safely, and remove dead ones.
1Why This Is Harder Than It Looks
A named query is a JPQL string registered under a name, such as Order.findOpen. Code refers to it in two ways. Plain JPA code calls createNamedQuery("Order.findOpen"), which a text search finds. But Spring Data also runs a named query implicitly when a repository method on the Order repository is called findOpen, with no string anywhere in the code that mentions Order.findOpen. A search for the name finds nothing and the query looks dead, yet deleting it breaks the repository at startup or, worse, switches the method to a derived query with different behaviour.
Names can also be built dynamically, such as entityName + ".findByStatus", and other modules or scheduled jobs may run queries we never see in this repository. So code search alone is not enough evidence.
2Gathering Usage Evidence
We combine three sources. Code search for createNamedQuery, @NamedQuery names, and repository methods whose names match a named query. Hibernate statistics in a test or staging environment, which record every query executed with its count and time. And production database statistics such as pg_stat_statements, which show the SQL that actually runs, over weeks.
| Status | Count | Action |
|---|---|---|
| Referenced and seen at runtime | 170 | Move next to the repository method |
| Referenced, never seen at runtime | 40 | Keep for now, check the code path |
| Near-duplicate of another query | 35 | Merge only with equivalence tests |
| No reference, no runtime evidence | 55 | Remove in small batches |
Hibernate statistics record queries by their text rather than by name, so we match them back to named queries by their JPQL, and the database view shows the generated SQL, which we match by tables and conditions. It is laborious, but the result is a table of 300 queries with a status: used in code, used at runtime, or no evidence of use. Statistics add overhead, so we enable them in staging or during test runs rather than permanently in production.
3Moving Live Queries to Their Repository Methods
For each used query, we choose a new home. Usually that is @Query on the Spring Data repository method that runs it, so the query sits next to its caller. If the module uses plain JPA or the team wants queries outside Java, META-INF/orm.xml is the other option; it keeps the same names, so callers do not change.
Notice the order of operations: we add the @Query first and delete the @NamedQuery in the same change. Because Spring Data checks @Query before named queries, the method switches to the new string immediately, and nothing is ever left without a query. Spring Data validates JPQL @Query strings at startup just as Hibernate validates named queries, so we keep the fail-fast behaviour.
4Merging Near-Duplicates Only With Proof
Near-duplicates are where clean-ups cause incidents. Order.findOpen orders by createdAt desc, Order.findOpenOrders orders by id, and Order.findActive has where o.status = 'OPEN' or o.status is null. They look interchangeable and are not: one caller depends on the ordering, another on the rows with a null status.
So before merging, we write a repository test on a real database, PostgreSQL in Testcontainers, with data that exercises the edges: ties in timestamps, null values, mixed case strings. The test runs both queries and asserts equal results including order. If they differ, we either keep both, renamed to say what they do, or change a caller deliberately with its owner's agreement.
5Removing Dead Queries in Small Steps
Queries with no reference and no runtime evidence for several weeks are removed, but in small changes, ten or twenty per commit, grouped by entity. Startup validation tells us immediately if something still referred to one by name, because a missing named query fails when its caller is created. A small change also means a rollback restores a handful of queries rather than undoing the whole clean-up.
Over time the entities shrink back to mappings, every live query has a test, and the duplicates either merged with proof or carry names that explain their difference.
6Follow-up questions
How long should we collect runtime evidence?
Long enough to cover the business cycle. Monthly invoicing, quarterly reports and year-end jobs may run rarely, so a few weeks can miss them. Asking the teams that own scheduled jobs, and checking schedulers for jobs in this module, fills the gaps before a removal.
Is orm.xml better than @Query for this clean-up?
orm.xml keeps the names, so callers using createNamedQuery need no change, and it removes the annotations from entities in one move. @Query is better for readers of Spring Data repositories because the query sits next to its method. Many teams use orm.xml as a first step and @Query as the final home.
Why not just delete everything unused at once?
Because our evidence is imperfect: a dynamic name or a rare job can make a used query look dead. Removing in small batches limits the impact of a mistake to a few queries and makes the cause obvious when something fails.
7Conclusion
In this answer, we cleaned up 300 named queries safely. We collected usage evidence from code search, Hibernate statistics and pg_stat_statements, moved live queries next to their repository methods with @Query or into orm.xml, merged near-duplicates only after tests on a real database proved equal results including ordering and nulls, relied on startup validation for typos and repository tests for behaviour, and removed dead queries in small, easily reverted changes.
Open with
I would start with evidence, because named queries are hard to trace: Spring Data runs Order.findOpen for a repository method called findOpen without the name appearing anywhere, so code search alone makes live queries look dead.
Then, if they want more
I would combine code search with Hibernate statistics in staging, which list every query executed with counts, and pg_stat_statements in production over several weeks, and end with a status for each query.
Live queries I would move next to their repository methods with @Query, adding the @Query and deleting the @NamedQuery in the same change, which is safe because Spring Data checks @Query first. If callers use createNamedQuery, orm.xml keeps the names and still clears the entities. Near-duplicates are the risky part.
I would merge two queries only after a repository test on a real PostgreSQL, through Testcontainers, proves they return the same rows in the same order, with edge cases like timestamp ties and nulls. Startup validation catches typos in JPQL, but behaviour needs those tests.
Dead queries I would remove ten or twenty at a time, so a rollback is small and the cause of any failure is obvious.
About this answer
- Last updated
- 12 November 2026
- Checked
- Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
- Where the question comes from
- Written by Scrivio for practice. It is not taken from an interview.
- Official documentation
- Spring Data JPA reference, Hibernate ORM documentation, Spring Framework reference, Transaction management
Report an issue with this answer
Copy the line below and send it to the author with what you found. It carries the address of this page.
Issue with "A legacy module has 300 @NamedQuery annotations spread over entities, some unused and...": https://scrivio-interview-library.netlify.app/databases/jpa-queries/dbe29aaded/