Scrivio Interview library
ScenarioAdvanced6 min read · updated 12 November 2026

Hibernate errors such as LazyInitializationException, N+1 queries and optimistic lock failures keep appearing in incident reviews across teams. What would you do as the senior engineer for the data layer?

I would treat these as a pattern, not as separate incidents. First collect the cases from incident reviews and code reviews and group them by cause, because most come from a few habits. Then set a handful of clear guidelines (DTO projections for reads, explicit fetch plans, open-in-view disabled, small transactions), back them with tooling that fails builds or flags staging (query count assertions, Hibernate statistics, slow query logs), teach them with examples from our own code, and review the data model for hot rows and oversized aggregates that no guideline can fix.

Why this question is asked

When the same three errors keep showing up in incident reviews across teams, fixing each one as it appears is like mopping the floor without closing the tap. A senior engineer for the data layer is expected to find the shared cause and change the system so the errors become rare and are caught before production. Interviewers ask this to see whether we can move from individual fixes to organisational ones without turning into a bureaucracy. In this answer, we will recap why these errors cluster, then walk through gathering evidence, writing guidelines that people can follow, adding tooling, training, and finally the model changes that remove the root cause.

1A Quick Recap: Why These Errors Travel Together

LazyInitializationException, N+1 queries and optimistic lock failures look unrelated, but they have common roots. The first two are both about the fetch plan, the decision of what data to load with a query. If nobody decides it explicitly, either lazy associations are touched too late (an exception) or touched one by one (N+1, one query for a list plus one per element). Optimistic lock failures usually come from transactions that are long or from entities that many requests write at once, which is a question of transaction size and data model.

So behind most incidents we expect to find a few habits: returning entities from services to controllers, relying on open-in-view, long transactions that call other services, and aggregates that include everything connected by a foreign key.

2Collect the Evidence

Before writing rules, we gather the facts. We read the last six months of incident reviews and pull Hibernate-related ones into a simple table: service, error, root cause, and how it was fixed. We add findings from code reviews and from production query logs, for example the top 20 statements by count. In a typical organisation this shows something like 40 percent N+1 from serializing entities, 25 percent lazy loading after the transaction, 20 percent optimistic lock conflicts on three specific entities, and a remainder of one-offs.

That table does two jobs. It tells us which few guidelines will remove most incidents, and it gives us real examples for training, which persuade far better than generic warnings.

3A Short Set of Guidelines

The guidelines must be few enough to remember. Reads that feed APIs use DTO projections or explicit fetch plans (JOIN FETCH or entity graphs), never lazy loading during serialization. spring.jpa.open-in-view is set to false in every service, so mistakes surface as clear exceptions in development. Transactions are small: they do database work only, and calls to other services or message brokers happen outside them. Every @ManyToOne is LAZY, because JPA makes it EAGER by default. And entities that are updated concurrently have @Version, with a documented choice between retry and 409.

Each guideline comes with the reason and a before-and-after example from our own code. People follow rules they understand and ignore rules that look arbitrary.

4Tooling That Catches Problems Early

Guidelines are enforced by tools wherever possible, because code review misses things. The most effective tool is a query count assertion in integration tests: the test loads a page of 20 orders and asserts that it took at most 2 statements. An N+1 regression then fails the build instead of reaching production.

Java
@Test
void orderListUsesConstantQueries() {
Statistics stats = emf.unwrap(SessionFactory.class).getStatistics();
stats.clear();
mockMvc.perform(get("/orders?size=20")).andExpect(status().isOk());
assertThat(stats.getPrepareStatementCount()).isLessThanOrEqualTo(2); // 2, not 21
}
Step throughHow each error is caught before production
  1. Guidelinesprojections, fetch plans, no open-in-view, small transactions
  2. Code review checklistthe same rules, with examples
  3. Integration testsquery count assertions with Hibernate statistics
  4. Stagingslow query logs, statistics per endpoint
  5. Productionmetrics for lock conflicts and query counts

5 layers, from the top down. Step through them one at a time.

Each layer catches what slipped through the one above.

This uses Hibernate statistics, enabled in tests with hibernate.generate_statistics=true. In staging we turn on slow query logging, both in Hibernate (hibernate.log_slow_query, with a threshold in milliseconds; check your version for the exact name) and in the database, and publish the counts per endpoint. Small library helpers and an ArchUnit-style rule that forbids returning entities from controllers complete the picture.

5Training With Our Own Code

A one-hour session per team, built from the evidence table, works better than a general JPA course. We take an incident from that team's own service, show the code, the SQL log with its 41 statements, and the fix with its 2 statements. Then the team fixes a similar case in a small exercise. Afterwards we keep a short internal page of these examples, and new joiners go through it. The aim is that developers read the SQL log as a normal part of their work, which is the single habit that prevents most of these incidents.

6Fixing the Model Where Rules Are Not Enough

Some problems are not habits but design. If optimistic lock failures concentrate on three entities, we look at why so many requests write them: perhaps an Account aggregate includes its entire transaction list and every new transaction bumps the account version, or a counter is read and written in Java instead of with an atomic UPDATE. We redesign those specific spots: smaller aggregates, references by id instead of mapped collections, atomic updates or separate counter rows. This work is targeted and tracked like any other technical debt, with the incident count for each entity as the measure of success.

Finally we track the outcome. If Hibernate-related incidents drop from, say, eight a quarter to two, the programme worked and can become routine; if not, the evidence table tells us what we missed.

7Follow-up questions

How do you get teams to adopt the guidelines without slowing them down?

By making the tools do most of the work: a shared test helper for query counts, a template with open-in-view disabled, and review checklists. Rules that come with ready-made helpers cost teams almost nothing to follow, and the incident data shows them the payoff.

Would you ban lazy loading?

No. Lazy loading is the right default for associations; the problem is unplanned lazy access. The rule is that each use case decides its fetch plan explicitly, and lazy loading outside a transaction fails loudly.

What if a team uses a different data access approach, such as jOOQ or plain JDBC?

That is fine and sometimes better for read-heavy services. The guidelines are about principles, explicit queries and small transactions, so they apply there too, and the query count tests work with any approach that goes through a DataSource proxy.

8Conclusion

In this answer, we treated recurring Hibernate errors as a system problem. We collected incidents and code review findings to see which habits cause most of them, wrote a short set of guidelines with reasons (DTO projections, explicit fetch plans, open-in-view off, small transactions), enforced them with query count tests, Hibernate statistics and slow query logs, trained teams with examples from their own code, and redesigned the hot rows and oversized aggregates behind the lock conflicts, measuring the incident rate to see if it worked.

What to say in the interviewAbout 80 seconds aloud

Open with

I'd treat it as one problem with a few causes rather than many separate incidents. First I'd collect the evidence: go through the incident reviews and code reviews, tag each Hibernate issue by root cause, and usually you find that most come from a few habits, like serializing entities, relying on open-in-view, long transactions, and a couple of hot entities.

Then, if they want more

Then I'd write a short set of guidelines with the reasons behind them: DTO projections or explicit fetch plans for reads, open-in-view disabled everywhere, all ManyToOne set to lazy, transactions that only do database work, and @Version with a clear retry-or-409 decision.

Rules alone don't stick, so I'd add tooling: query count assertions in integration tests using Hibernate statistics, so an N+1 regression fails the build, plus slow query logging and statistics in staging. I'd run short training sessions per team using their own incidents, showing the SQL log before and after, so reading the SQL becomes a habit.

And for the lock failures, I'd review the data model itself, looking for hot rows and oversized aggregates, and fix those with smaller aggregates or atomic updates. I'd measure success by the number of Hibernate-related incidents per quarter.

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.
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 "Hibernate errors such as LazyInitializationException, N+1 queries and optimistic lock...": https://scrivio-interview-library.netlify.app/databases/jpa-fundamentals/dc4c39aa73/