Quick revision
The short answer
First, make sure every JPQL query is checked: JPQL in @Query is validated when the repository is created, so a CI job that starts the full Spring context against the real schema catches most breakage before any deployment. Native queries are not validated, so they need integration tests against the real database engine with Testcontainers, and a rule that every new query method comes with such a test. Then reduce the volume of strings by extracting repeated filters into Specifications or shared fragments, and move areas with frequent schema change to a type-safe query approach.
What to remember
In this answer, we saw that JPQL queries are parsed at startup against entities but not against the database, and native queries are not checked at all, which is why failures appear at runtime and only where a broken path runs. The plan is to start the full context in CI against a migrated schema with validation, smoke-test and then properly test native queries with Testcontainers, require a test for every new query, extract duplicated filters into Specifications or shared fragments, and use type-safe queries where the schema changes most.
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.
First, make sure every JPQL query is checked: JPQL in @Query is validated when the repository is created, so a CI job that starts the full Spring context against the real schema catches most breakage before any deployment. Native queries are not validated, so they need integration tests against the real database engine with Testcontainers, and a rule that every new query method comes with such a test. Then reduce the volume of strings by extracting repeated filters into Specifications or shared fragments, and move areas with frequent schema change to a type-safe query approach.
Why this question is asked
A codebase with hundreds of untested query strings is common in older Spring applications. Each query was written to solve one problem, filters were copied from method to method, and the only test was that the feature worked when it was built. Then the schema changes, a column is renamed in a migration, and some environments break at runtime while others do not, depending on which code paths run there. Interviewers ask this scenario at a senior level to see whether we can turn a messy situation into an ordered plan: what gives the most safety soonest, what reduces the problem over time, and what stops it from coming back. In this answer, we will understand why the breakage appears only at runtime and only in some places, then add the safety nets in order of value, reduce duplication, and decide where type-safe queries are worth it.
1Why the Breakage Appears Only at Runtime
Two kinds of query strings live in @Query. JPQL strings talk about entities and fields. When Spring Data creates a repository at startup, it asks Hibernate to parse each JPQL query, and Hibernate checks that every entity and field exists. So a JPQL query that refers to a removed field fails the application start.
But that check is against the entity classes, not the database. If a migration renames the column created_at to created_on and nobody updates the @Column mapping, every JPQL query still parses; the SQL Hibernate generates simply names a column that no longer exists, and the error comes when the query runs.
Native SQL strings are not parsed at all. Hibernate hands them to the database when the method is called. A wrong column name is found the first time that code path runs, which may be a nightly batch in one environment and never in another. That explains why the failures are scattered: they surface wherever and whenever a broken query happens to run.
| Kind of change | JPQL @Query | Native @Query |
|---|---|---|
| Field removed from entity | Startup fails | Not caught until it runs |
| Column renamed, mapping not updated | Not caught until it runs | Not caught until it runs |
| Typo in the query string | Startup fails | Not caught until it runs |
| Wrong result, valid SQL | Only a test catches it | Only a test catches it |
2Start the Full Context Against the Real Schema in CI
The cheapest safety net uses what already exists. If CI starts the complete Spring context, every repository is created, every JPQL query is parsed, and a broken one fails the build. Many projects never get this check because their tests use slices that load only some beans, or mock repositories entirely.
Then add schema validation. Run the real migrations, Flyway or Liquibase, on a fresh database of the same engine as production, and set Hibernate to validate the mappings against it with spring.jpa.hibernate.ddl-auto=validate. Hibernate compares every entity mapping with the actual tables and columns and fails the start if a mapped column is missing. That catches the renamed-column case for all JPQL and derived queries at once.
This single test, which takes a minute to write, turns most of the scattered runtime failures into a red build.
3Integration Tests for Native Queries
Native queries still slip through, because nothing parses them until they run. They need tests that run them against the same engine as production; an in-memory database such as H2 accepts different SQL and would give false confidence. Testcontainers starts a real PostgreSQL or MySQL in Docker for the test.
With hundreds of queries, we cannot write all the tests at once, so order the work by risk. First, a smoke test that calls every native query method once with simple parameters, which can even be generated by reflection over the repository interfaces; it proves the SQL is valid against the current schema. Then proper tests, with data and expected results, for the queries behind important features and the ones that broke before.
4Stop the Problem Growing
Once the nets exist, add a rule so the gap does not reopen: every new or changed query method comes with an integration test, and reviewers check for it. A simple build check can help, for example a test that lists all methods with nativeQuery = true and fails if one has no test referencing it by name.
5Remove Duplicated Filters
Duplicated filters are the reason one schema change breaks thirty queries. If the rule for an active customer, status = 'ACTIVE' and deleted = false and region in the allowed list, is copied into every query, every copy must be found and changed. The fix is to express each filter once.
For dynamic JPA queries, Spring Data Specifications fit well: each filter is a small reusable object, and queries combine them. The rule then lives in one place, and changing it changes every query that uses it.
For native SQL, the equivalent is a database view or a shared SQL fragment in a query class. The goal is the same: one definition of each business filter.
6Type-Safe Queries Where the Schema Moves
Some areas change their schema every few weeks. There, even tested strings are expensive: each change means finding and updating strings by hand and waiting for tests to tell us what we missed. A type-safe approach moves that work to the compiler. Specifications with the JPA static metamodel, where Order_.createdAt replaces the string "createdAt", or Querydsl, check entity fields at compile time. jOOQ generates classes from the database schema itself, so a renamed column breaks compilation everywhere it is used.
I would not convert the whole codebase. I would pick the two or three modules with the most schema churn and query breakage, convert them, measure the change in incidents and effort, and decide from there.
- Start full context in CIParses every JPQL query
- Validate mappings against migrated schemaddl-auto=validate on a real engine
- Smoke-test every native queryTestcontainers, same engine as production
- Require a test for each new queryReview rule plus a build check
- Extract shared filtersSpecifications, views, fragments
- Type-safe queries for high-churn areasMetamodel, Querydsl or jOOQ
6 steps in order. Play them, or step through them one at a time.
The first two steps catch most failures within a day of work.
7Follow-up questions
Why not use H2 for these tests to keep them fast?
Because H2 accepts different SQL and behaves differently for types, functions and locking. A native query that passes on H2 can fail on PostgreSQL. Testcontainers with a reused container per test run keeps the cost to a few seconds and tests the real thing.
Is ddl-auto=validate safe in production?
Validation only reads the schema and fails the start on a mismatch; it never changes tables. Some teams enable it in production too as a last guard, while others keep it to CI and staging to avoid blocking a deployment on a harmless difference. Either way, never use update or create outside development.
8Conclusion
In this answer, we saw that JPQL queries are parsed at startup against entities but not against the database, and native queries are not checked at all, which is why failures appear at runtime and only where a broken path runs. The plan is to start the full context in CI against a migrated schema with validation, smoke-test and then properly test native queries with Testcontainers, require a test for every new query, extract duplicated filters into Specifications or shared fragments, and use type-safe queries where the schema changes most.
Open with
I would start by explaining why it happens. JPQL in @Query is parsed by Hibernate when the repository is created, but only against the entity classes, so a renamed column with a stale mapping still passes.
Then, if they want more
Native SQL is not parsed at all, so a broken native query fails the first time it runs, which might be one nightly job in one environment. That is why the failures look random.
My first step would be cheap and broad: a CI test that starts the full Spring context against a real database of the same engine, with the real Flyway or Liquibase migrations applied and ddl-auto set to validate.
That parses every JPQL query and checks every mapping against the actual schema, so most breakage becomes a red build within a day. Second, native queries get integration tests with Testcontainers: a smoke test that calls every native method once to prove the SQL is valid, and real tests with data for the important ones.
Third, a rule that every new or changed query method comes with an integration test, backed by a build check if possible. Then I would reduce the problem itself: duplicated filters are why one schema change breaks thirty queries, so I would extract them into Specifications, or views and shared fragments for native SQL.
Finally, for the modules with the most schema churn, I would pilot a type-safe approach, the JPA metamodel, Querydsl or jOOQ, and measure whether incidents drop before going further.
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 large codebase has hundreds of @Query strings with duplicated filters and no tests....": https://scrivio-interview-library.netlify.app/databases/spring-data-jpa/4c56785404/