Scrivio Interview library
DesignIntermediate7 min read · updated 12 November 2026

A team uses JPA everywhere but has slow reporting queries and complex upserts. When would you mix JdbcTemplate or JdbcClient into a JPA service, and what pitfalls must you watch?

We bring JdbcTemplate or JdbcClient into a JPA service for read-heavy reports, bulk operations and database-specific SQL such as upserts, where loading and tracking entities adds cost and no value. Under JpaTransactionManager both share the same transaction and connection, so they commit together. The pitfalls are about the persistence context: pending JPA changes are invisible to JDBC until we flush, JDBC writes are not reflected in already loaded entities or the second-level cache, and SQL scattered across the codebase spreads schema knowledge, so we keep it in one place per aggregate.

Why this question is asked

JPA is excellent at loading an aggregate, changing it and saving it, which is most of what business code does. It is much less good at summing a million rows, updating 50,000 rows at once, or using a database feature like INSERT ... ON CONFLICT. Teams that use JPA for everything often end up with slow reports and convoluted upsert logic. Interviewers ask this design question to see whether we know where each tool fits and what goes wrong when we mix them. In this answer, we will see where JPA struggles, choose the jobs for JDBC, show that both share one transaction, and then go through the flush and stale-entity pitfalls and how to organise the SQL.

1Where JPA Struggles

JPA, through Hibernate, keeps a persistence context: a per-transaction map of every entity it has loaded, with a snapshot of its original state. At flush time, it compares each entity with its snapshot to find changes, which is called dirty checking. That is perfect for a use case that loads one order, changes its status and saves it.

For a report, the same machinery is pure overhead. Loading 200,000 order entities to compute totals per region creates 200,000 objects, 200,000 snapshots, and possibly lazy-loading queries for associations, only to throw them all away. A single SQL query with GROUP BY returns a few dozen rows and lets the database do the work. Similarly, a bulk price change through entities means loading each row and updating it one at a time, while one UPDATE statement changes them all. And some SQL features, such as PostgreSQL's INSERT ... ON CONFLICT or window functions, have no natural JPQL form.

2Choosing the Jobs for JDBC

So we keep JPA for the aggregate's normal lifecycle and use JdbcClient for three kinds of work: read-heavy reports and projections that map rows straight into DTOs or records, bulk updates and deletes over many rows, and database-specific statements such as upserts.

Java
@Repository
class OrderReportQueries {
private final JdbcClient jdbc;
OrderReportQueries(JdbcClient jdbc) { this.jdbc = jdbc; }
List<RegionTotal> totalsByRegion(LocalDate from) {
return jdbc.sql("""
select c.region, count(*) as orders, sum(o.total) as revenue
from orders o join customer c on c.id = o.customer_id
where o.created_at >= :from
group by c.region order by revenue desc""")
.param("from", from)
.query(RegionTotal.class)
.list(); // [RegionTotal[region=West, orders=81234, revenue=...], ...]
}
int upsertStock(long sku, int qty) {
return jdbc.sql("""
insert into stock(sku, qty) values (:sku, :qty)
on conflict (sku) do update set qty = stock.qty + excluded.qty""")
.param("sku", sku).param("qty", qty)
.update(); // 1, whether inserted or updated
}
}
Which tool for which job
JobJPAJdbcClient
Load, change and save one aggregatebest fitmore code, no benefit
Report over many rowsslow: entities, snapshotsbest fit: SQL to records
Bulk update or deleterow by row, or JPQL bulkone statement
Upsert (ON CONFLICT, MERGE)awkward, racybest fit
Complex query with window functionsnative query at bestbest fit
Use JPA for aggregates and JDBC where tracking entities adds nothing.

Notice that the report returns records, not entities, so nothing is tracked, and the upsert does in one statement what would otherwise need a find, a branch and a save, with a race between them.

3Both Share One Transaction

Mixing is safe at the transaction level because, under JpaTransactionManager, a JDBC call inside a @Transactional method uses the same database connection as Hibernate. The transaction manager begins the JPA transaction, asks Hibernate's dialect for the underlying JDBC connection, and binds that connection to the thread for the DataSource. JdbcTemplate and JdbcClient look up the bound connection through DataSourceUtils, find it, and use it. So JPA changes and JDBC statements commit or roll back together.

The condition is that JDBC uses the same DataSource as the EntityManagerFactory, which is the default in Spring Boot. If a second DataSource or a separately created JdbcTemplate points elsewhere, its statements run in their own auto-commit transactions, which is a hard bug to spot.

4Pitfall 1: Pending JPA Changes Are Invisible to JDBC

Hibernate does not send an UPDATE when we change an entity. It waits until flush, which happens at commit, before a JPQL or HQL query that touches the affected tables, or when we call flush() ourselves. JdbcClient runs its SQL directly on the connection, and Hibernate knows nothing about it, so it does not flush first.

Java
@Transactional
public void closeAndReport(long orderId) {
Order o = orderRepository.findById(orderId).orElseThrow();
o.setStatus(CLOSED); // only in the persistence context so far
long open = jdbc.sql("select count(*) from orders where status = 'OPEN'")
.query(Long.class).single(); // still counts this order as OPEN
entityManager.flush(); // send the pending UPDATE now
long openAfter = jdbc.sql("select count(*) from orders where status = 'OPEN'")
.query(Long.class).single(); // now one fewer
}

So before a JDBC read that must see changes made through JPA in the same transaction, we call entityManager.flush(). The flush sends the SQL but does not commit, so the work is still rolled back together if the method fails.

5Pitfall 2: JDBC Writes Are Not Reflected in Loaded Entities

The reverse problem is just as real. If we update rows with JDBC, any entity already loaded in the persistence context keeps its old values, and Hibernate will happily return that stale object from find(). Worse, if the stale entity is dirty, a later flush can overwrite the JDBC change. The second-level cache, if enabled, is also unaware of the JDBC write and keeps serving the old data to other transactions.

The fixes depend on scope. For one entity, entityManager.refresh(entity) reloads it. For a bulk change, entityManager.clear() empties the persistence context after flushing, so later reads go to the database. For the second-level cache, we evict the affected region through the cache API, for example entityManagerFactory.getCache().evict(Order.class). The simplest policy is to run bulk JDBC operations at the start of a transaction, or in their own transaction, before loading entities of the same tables.

Step throughStale entity after a JDBC update
ServicePersistence contextJdbcClientDatabase
find(Order 7): loaded, status OPEN
update orders set status = 'CLOSED' where id = 7
row 7 is CLOSED in the database
find(Order 7) again
cached entity: status OPEN (stale)
refresh(order) or clear()
select row 7
status CLOSED

8 messages in order. Play them, or step through them one at a time.

The persistence context answers from memory until we refresh or clear it.

6Keep the SQL in One Place per Aggregate

The last pitfall is organisational. If report queries and upserts are written inline in controllers and services all over the codebase, knowledge of the schema spreads everywhere, and a column rename turns into a search through dozens of files, with no compile-time help. So we give each aggregate a single home for its SQL, such as OrderReportQueries next to the OrderRepository, and test those classes against the real database with Testcontainers. Database migrations, with Flyway or Liquibase, stay the single source of truth for the schema, and the tests catch drift between the SQL and the schema before production does.

7Follow-up questions

Does Hibernate flush automatically before a native query?

With Hibernate's native API, a native SQL query run through the session triggers an auto-flush in many cases, and with JPA's native queries the behaviour depends on the flush mode and Hibernate version, so check yours. But JdbcTemplate and JdbcClient go around Hibernate entirely, so there is never an automatic flush for them. Calling flush() explicitly is the reliable approach.

Why not use JPQL bulk updates instead of JDBC?

JPQL bulk updates, @Modifying queries in Spring Data, are fine for simple bulk changes and stay inside JPA. They have the same stale-entity problem, which is why @Modifying has clearAutomatically and flushAutomatically options. For database-specific SQL such as upserts or window functions, JPQL is not expressive enough, and JDBC is clearer.

Would Spring Data JPA projections be enough for reports?

Interface or DTO projections avoid loading full entities and are a good first step for simple reports. When the report needs grouping, window functions, CTEs or tuning with database-specific hints, plain SQL through JdbcClient is easier to read, review and optimise.

8Conclusion

In this answer, we saw that JPA's persistence context makes it great for loading and saving aggregates and wasteful for reports, bulk changes and upserts, which are better done with JdbcClient or JdbcTemplate. Under JpaTransactionManager both share the same connection and transaction. The pitfalls are that pending JPA changes need a flush before JDBC can see them, that JDBC writes leave loaded entities and the second-level cache stale until we refresh, clear or evict, and that SQL should live in one tested place per aggregate.

What to say in the interviewAbout 90 seconds aloud

Open with

I would keep JPA for what it does well, loading an aggregate, changing it and saving it, and bring in JdbcClient for three kinds of work. First, read-heavy reports, where SQL with grouping maps straight into records and we avoid creating and dirty-checking hundreds of thousands of entities.

Then, if they want more

Second, bulk updates and deletes, which are one statement instead of row-by-row saves. Third, database-specific SQL like PostgreSQL's insert on conflict for upserts, which removes the find-then-save race. Mixing is safe transactionally: under JpaTransactionManager, the JDBC calls use the same connection Hibernate uses, as long as they share the DataSource, so everything commits or rolls back together.

The pitfalls are about the persistence context. Hibernate only sends changes at flush, so if I modify an entity and then run a JDBC query in the same transaction, the query does not see the change unless I call entityManager.flush first.

In the other direction, a JDBC update does not touch entities already loaded, so find returns stale data and a later flush might even overwrite the change; I would refresh the entity, clear the persistence context after bulk work, and evict the second-level cache region if it is enabled.

Finally, I would keep the SQL for each aggregate in one class next to its repository, tested against the real database with Testcontainers, so schema knowledge does not spread across the codebase.

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
java.sql, package documentation
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 team uses JPA everywhere but has slow reporting queries and complex upserts. When...": https://scrivio-interview-library.netlify.app/databases/jdbc/76b8078821/