Quick revision
The short answer
A native SQL query is the right tool when we need a feature that only our database offers, such as an upsert, JSON operators, a recursive query, an optimizer hint or a window function our HQL version cannot express. In exchange we lose portability across databases and the startup check of the query against our entity model, we must map results ourselves, and Hibernate can no longer tell which tables the query touches, which affects automatic flushing and second-level cache invalidation.
What to remember
In this answer, we saw that native SQL is appropriate when we need a database-specific feature such as an upsert, JSON operators, recursive queries, hints or window functions our HQL version lacks. The price is lost portability, no startup check against the entity model, manual mapping of entity and DTO results, and Hibernate flushing more and invalidating more cache than necessary because it cannot see which tables are affected. Keeping native queries in repositories and covering each with a test against the real database keeps that price under control.
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.
A native SQL query is the right tool when we need a feature that only our database offers, such as an upsert, JSON operators, a recursive query, an optimizer hint or a window function our HQL version cannot express. In exchange we lose portability across databases and the startup check of the query against our entity model, we must map results ourselves, and Hibernate can no longer tell which tables the query touches, which affects automatic flushing and second-level cache invalidation.
Why this question is asked
Almost every real JPA application ends up with a few native queries, and many end up with far too many. Interviewers ask this question to see whether we treat native SQL as a deliberate choice with known costs, or as an escape hatch we reach for whenever JPQL feels awkward. In this answer, we will recap what JPQL and native SQL are, look at the cases where native SQL earns its place, go through what we give up when we use it, see how result mapping and Hibernate's flushing change, and finish with how to keep native queries safe in a codebase.
1A Quick Recap of JPQL and Native SQL
JPQL, the Jakarta Persistence Query Language, is a query language written against our entity classes rather than our tables. We write select o from Order o where o.status = :status, and Hibernate translates it into the SQL dialect of whatever database we run on. HQL, Hibernate's own query language, is a superset of JPQL with extra features.
A native query is plain SQL that we hand to the database exactly as written. Hibernate does not parse it into its own model; it only binds the parameters, sends the statement over JDBC and maps whatever rows come back. In Spring Data JPA we mark such a query with nativeQuery = true on @Query.
Both methods return the same orders here, so for this query the JPQL version is the better one. Native SQL becomes interesting only when the SQL we need has no JPQL equivalent.
2When Native SQL Earns Its Place
The honest reason to write native SQL is that the database can do something JPQL cannot ask for. PostgreSQL's insert ... on conflict do update performs an upsert in one atomic statement. Its JSON operators such as ->> and @> query inside a jsonb column. A recursive common table expression walks a category tree in one round trip. Optimizer hints, full-text operators and lateral joins are other examples.
Window functions, functions such as row_number() over (partition by ...) that compute a value across a group of rows without collapsing them, are a good example of a moving line. Hibernate 6 added window functions and common table expressions to HQL, so many queries that once needed native SQL can now stay in HQL. On an older Hibernate, or for a vendor-specific variant, native SQL is still the way. Check what your Hibernate version supports before assuming native SQL is required.
Notice that this query relies on two things that are specific to PostgreSQL or newer HQL: the ->> operator and the window function. That is the shape of a good native query. It does something the database is good at and that our query language cannot say.
3What We Give Up
The first cost is portability. The query above runs only on PostgreSQL. If we ever run tests on H2 or move to another engine, every native query must be checked and many must be rewritten. JPQL queries move with the dialect for free.
The second cost is checking. Spring Data parses every JPQL @Query at startup and Hibernate validates it against the entity model, so a misspelled field such as o.custmer fails the application before it serves a single request. A native query is just a string to Hibernate. A typo in a column name, or a column renamed by a migration, only fails when that query actually runs, possibly in production on a rarely used path.
The third cost is mapping, which we look at next, and the fourth is that Hibernate loses track of which tables the statement reads and writes.
| Concern | JPQL / HQL | Native SQL |
|---|---|---|
| Database features | Portable subset (more in Hibernate 6) | Everything the engine offers |
| Portability | Follows the dialect | Tied to one engine |
| Checked at startup | Yes, against the entity model | No, fails when it runs |
| Result mapping | Entities and DTOs by constructor | All columns for entities; DTOs need mapping |
| Flush and cache | Hibernate knows the tables | Hibernate must assume the worst |
4Mapping the Results
When a native query returns an entity type, the result set must contain every column the entity maps, with the column names Hibernate expects. If we select only id and total into an Order, Hibernate fails because it cannot find the other columns. That is why entity-returning native queries usually select o.* from the table.
For a smaller result, a DTO, a plain object that carries just the fields we need, works better, but we must tell JPA how to build it. Spring Data can map native results into an interface projection by matching column aliases to getter names. For a class or record we can use @SqlResultSetMapping with @ConstructorResult, or read a Tuple and build the object ourselves.
The aliases are the contract here. If someone renames the alias to order_id, getId() silently returns null instead of failing, so these mappings need tests.
5Why Hibernate Flushes Everything and Clears the Cache
Before running a JPQL query, Hibernate checks which tables the query reads, and flushes pending changes, the inserts and updates held in the persistence context that have not reached the database yet, only if they touch those tables. For a native query it cannot know which tables are involved, so in JPA mode it flushes all pending changes first, to be safe. That can cause surprising SQL in the middle of a read.
The same blindness hits the second-level cache, a cache of entity data shared across sessions. After a JPQL bulk update Hibernate evicts only the affected entity's region. After a native update it does not know which entities changed, so by default it invalidates every cache region. Hibernate's NativeQuery API lets us declare the affected tables or entities with addSynchronizedEntityClass, which narrows both the flush and the eviction.
6Keeping Native Queries Safe
A sensible rule is to keep native SQL inside repositories, never scattered in services, so all database-specific code sits in one layer we can find and review. Each native query then needs an integration test against the real database engine, for example PostgreSQL started with Testcontainers, because an in-memory database would either reject the SQL or run it with different semantics.
These tests are what replaces the startup check we lost. They catch renamed columns, wrong aliases and changed behaviour after an upgrade, and they make a later engine move measurable rather than a guess.
7Follow-up questions
Does Spring Data validate native queries at startup?
No. For a JPQL @Query, Spring Data asks the EntityManager to create the query while the application starts, so syntax and model errors fail fast. A native query is only checked by the database when it runs. That is the main reason every native query should have an integration test that executes it.
Can we avoid the full flush before a native query?
Yes. With Hibernate's NativeQuery we can call addSynchronizedEntityClass or addSynchronizedQuerySpace to name the tables involved, so Hibernate flushes and evicts only what is related. We can also change the flush mode for that query, but then we must be sure the query does not need to see pending changes.
8Conclusion
In this answer, we saw that native SQL is appropriate when we need a database-specific feature such as an upsert, JSON operators, recursive queries, hints or window functions our HQL version lacks. The price is lost portability, no startup check against the entity model, manual mapping of entity and DTO results, and Hibernate flushing more and invalidating more cache than necessary because it cannot see which tables are affected. Keeping native queries in repositories and covering each with a test against the real database keeps that price under control.
Open with
I use native SQL when the query needs something only the database can do: an upsert with on conflict, jsonb operators, a recursive CTE, an optimizer hint, or a window function if our Hibernate version cannot express it.
Then, if they want more
Hibernate 6 added window functions and CTEs to HQL, so I check that first. The costs are clear to me. The query is tied to one engine, and it is not validated at startup the way a JPQL @Query is, so a renamed column only fails when the query runs.
Mapping is on me: an entity result needs every mapped column, and a DTO needs an interface projection with matching aliases or a result set mapping.
Hibernate also cannot tell which tables a native query touches, so it flushes all pending changes before running it, and after a native update it invalidates the whole second-level cache unless I declare the synchronized entities.
So my rule is to keep native queries inside repositories, keep them few and deliberate, and give every one an integration test against the real engine using Testcontainers, which replaces the safety net we lose when we leave JPQL.
About this answer
- Last updated
- 12 November 2026
- Versions it names
- Hibernate 6
- 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 "When is a native SQL query appropriate in a JPA application, and what do you lose...": https://scrivio-interview-library.netlify.app/databases/jpa-queries/617994d8ee/