All specialtiesTechnology · Job interview

Hibernate / JPA

Hibernate questions test whether you know what the ORM does behind your repository methods. Say clearly what happens in memory and what happens in the database.

Words → phrases → sentences → speaking

Try SpeakRole ↗
Job interviewHibernate / JPA
V

What is the N+1 problem in JPA, and how do you avoid it?

0:18
Interviewer question

Hibernate / JPA

JPA is the specification, and Hibernate is the most common implementation. Interviewers want to hear that you understand the persistence context, when SQL is actually sent, and how an ORM can hurt performance when it is used carelessly.

A reliable structure for a spoken answer is: what the feature does, the problem it can cause in a real service, and how you fix or avoid it. Use a short example, such as an order with a list of items, because a concrete picture is easier to explain aloud.

  • ✓Words → phrases → sentences → speaking
  • ✓Answer meaning
  • ✓Language

Common questions and sample answers

What is the persistence context, and what states can an entity have?

What the interviewer wants to hear. The persistence context as a first-level cache and unit of work, the four states, and what dirty checking means.

Sample answer to practise aloud

The persistence context is the set of entities that an entity manager is currently tracking, usually inside one transaction. It works as a first-level cache, so loading the same row twice gives the same object. An entity can be transient, which means it is new and not tracked, managed, detached after the session is closed, or removed. For managed entities, Hibernate does dirty checking. If I change a field, I do not need to call save. At flush time, Hibernate compares the state and sends an update. This is convenient, but it can surprise people who do not expect a change to be written.

What is the difference between lazy and eager loading, and what is LazyInitializationException?

What the interviewer wants to hear. Default fetch types, proxies, and a sensible fix. A good answer does not simply switch everything to eager.

Sample answer to practise aloud

With lazy loading, Hibernate does not load an association until I use it. It puts a proxy or a placeholder collection there, and the query runs on the first access. With eager loading, the data is loaded together with the parent. By default, collections are lazy, and to-one associations such as ManyToOne are eager. LazyInitializationException happens when I touch a lazy association after the session is closed, so there is no connection to load it. The wrong fix is to make everything eager, because it loads too much. I prefer to load exactly what the use case needs, with a fetch join, an entity graph or a DTO query.

What is the N+1 problem, and how do you solve it?

What the interviewer wants to hear. A clear example, how to detect it with SQL logs or query counts, and more than one fix with a caveat.

Sample answer to practise aloud

The N+1 problem happens when I load a list of N parents with one query, and then Hibernate runs one more query for each parent to load its lazy children. So a hundred orders mean 101 queries. I detect it by turning on SQL logging in a test or by counting queries. To fix it, I can use a join fetch, an entity graph or a batch size setting, which loads children for several parents at once. For read-only screens, a DTO projection is often the cleanest. One caveat is that a join fetch of a collection together with pagination can force paging in memory, so I always test that case.

How do you handle concurrent updates to the same entity?

What the interviewer wants to hear. Optimistic versus pessimistic locking, when each is appropriate, and short transactions.

Sample answer to practise aloud

I use optimistic locking in most cases. I add a version field with the Version annotation. When Hibernate updates the row, it checks that the version is unchanged. If another transaction changed it first, the update fails with an optimistic lock exception, and I retry or ask the user to reload. It needs no database locks, so it scales well when conflicts are rare. When conflicts are frequent, for example when many requests change one balance, I can use pessimistic locking, which locks the row with select for update. The price is waiting and a risk of deadlocks, so I keep such transactions short.

How does caching work in Hibernate?

What the interviewer wants to hear. First-level versus second-level cache, the fact that the second level is optional, and the risk of stale data.

Sample answer to practise aloud

There are two levels. The first-level cache is the persistence context. It is always on, it belongs to one session and lives as long as the session. The second-level cache is optional and is shared between sessions. It needs a cache provider and has to be enabled for specific entities. It can reduce database reads for data that is read often and rarely changed, like a list of countries. The risk is stale data, especially when several application nodes or other systems write to the same tables. There is also a query cache, but it is invalidated whenever the tables change, so it helps less often. I enable caches only after I have measured a real problem.

How to say the key terms

Hibernate
HY-ber-nayt
entity
EN-tih-tee
JPA
J-P-A
ORM
O-R-M
lazy
LAY-zee
detached
dih-TACHT
cascade
kas-KAYD

Useful phrases for answering

  • At flush time, Hibernate…
  • The entity is managed, so the change is tracked.
  • I would check the generated SQL first.
  • The number of queries grows with the number of rows.
  • I load exactly what the use case needs.
  • The trade-off is convenience against control.
  • I would measure before I enable a cache.

Common mistakes to avoid

  • Calling the ORM "slow". Say what exactly is slow: too many queries, too much data loaded or long transactions. Then say how you found it.
  • Fixing every lazy-loading error by switching to eager loading. It hides the problem and loads more data than needed.
  • Mixing up JPA and Hibernate. JPA is the standard API, and Hibernate is one implementation with extra features. Say which one a feature belongs to.
  • Saying that the save method writes to the database immediately. Hibernate may delay the SQL until flush or commit, so explain the difference between a tracked change and the actual statement.
  • Stressing the wrong syllable in "Hibernate". The stress is on the first one: HY-ber-nayt. It is the main word of this interview, so say it with confidence.

Frequently asked questions

Do I need to know Hibernate if I use Spring Data JPA?

Yes. Spring Data JPA hides much of the code, but the persistence context, lazy loading and the N+1 problem still apply. Interviewers often ask about Hibernate behaviour through repository examples.

Should I return entities directly in REST responses?

Usually it is better to return DTOs. Entities can expose fields you do not want to share, trigger lazy loading during serialisation and tie your API to your database model. Say that you map entities to DTOs at the service boundary.

How do I describe an ORM performance problem I solved?

Use a short story: the symptom, such as a slow page, how you counted the queries, the change you made, for example a fetch join, and the result. Give a number you really measured, like the query count before and after.

Reading an answer is not the same as saying it. Practise each question out loud, then compare the meaning and the language of your own answer.

Try SpeakRole ↗

Other topics in this area