Tutte le specialitàTecnologia · Colloquio di lavoro

Hibernate / JPA

Le domande su Hibernate verificano se sai che cosa fa l'ORM dietro i metodi del tuo repository. Di' con chiarezza che cosa succede in memoria e che cosa succede nel database.

Parole → espressioni → frasi → parlato

Prova SpeakRole ↗
Colloquio di lavoroHibernate / JPA
V

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

0:18
Domanda dell’intervistatore

Hibernate / JPA

JPA è la specifica e Hibernate è l'implementazione più diffusa. Chi intervista vuole sentire che capisci il persistence context, quando l'SQL viene davvero inviato e come un ORM può peggiorare le prestazioni se usato con leggerezza.

Una struttura affidabile per una risposta orale è: che cosa fa la funzionalità, il problema che può causare in un servizio reale e come lo risolvi o lo eviti. Usa un breve esempio, come un ordine con un elenco di articoli, perché un'immagine concreta è più facile da spiegare a voce.

  • ✓Parole → espressioni → frasi → parlato
  • ✓Senso della risposta
  • ✓Lingua

Domande comuni e risposte di esempio

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

Che cos'è il persistence context e quali stati può avere un'entity?

Che cosa vuole sentire l'intervistatore. Il persistence context come cache di primo livello e unità di lavoro, i quattro stati e che cosa significa dirty checking.

Risposta di esempio in inglese da esercitare ad alta voce

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?

Qual è la differenza tra lazy ed eager loading e che cos'è LazyInitializationException?

Che cosa vuole sentire l'intervistatore. I fetch type predefiniti, i proxy e una correzione sensata. Una buona risposta non si limita a passare tutto a eager.

Risposta di esempio in inglese da esercitare ad alta voce

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?

Che cos'è il problema N+1 e come lo risolvi?

Che cosa vuole sentire l'intervistatore. Un esempio chiaro, come individuarlo con i log SQL o contando le query, e più di una soluzione con la relativa avvertenza.

Risposta di esempio in inglese da esercitare ad alta voce

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?

Come gestisci gli aggiornamenti concorrenti della stessa entity?

Che cosa vuole sentire l'intervistatore. Locking ottimistico contro pessimistico, quando è adatto ciascuno e transazioni brevi.

Risposta di esempio in inglese da esercitare ad alta voce

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?

Come funziona la cache in Hibernate?

Che cosa vuole sentire l'intervistatore. Cache di primo contro secondo livello, il fatto che il secondo livello è opzionale e il rischio di dati obsoleti.

Risposta di esempio in inglese da esercitare ad alta voce

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.

Come pronunciare i termini chiave

Hibernate
hài-ber-neit
entity
èn-ti-ti
JPA
gèi-pi-èi
ORM
ou-àr-èm
lazy
lèi-zi
detached
di-tàc-t (la «c» è quella di «cena»)
cascade
cas-chèid

Frasi utili per rispondere

  • At flush time, Hibernate…Al momento del flush, Hibernate…
  • The entity is managed, so the change is tracked.L'entity è managed, quindi la modifica viene tracciata.
  • I would check the generated SQL first.Controllerei prima l'SQL generato.
  • The number of queries grows with the number of rows.Il numero di query cresce con il numero di righe.
  • I load exactly what the use case needs.Carico esattamente ciò che serve al caso d'uso.
  • The trade-off is convenience against control.Il compromesso è tra comodità e controllo.
  • I would measure before I enable a cache.Misurerei prima di attivare una cache.

Errori comuni da evitare

  • Definire l'ORM «lento». Di' che cosa è lento esattamente: troppe query, troppi dati caricati o transazioni lunghe. Poi di' come lo hai scoperto.
  • Correggere ogni errore di lazy loading passando a eager loading. Nasconde il problema e carica più dati del necessario.
  • Confondere JPA e Hibernate. JPA è l'API standard, Hibernate è un'implementazione con funzionalità in più. Di' a quale dei due appartiene una funzionalità.
  • Dire che il metodo save scrive subito sul database. Hibernate può rimandare l'SQL al flush o al commit, quindi spiega la differenza tra una modifica tracciata e l'istruzione effettiva.
  • Mettere l'accento sulla sillaba sbagliata in "Hibernate", per esempio sulla seconda come nell'italiano «ibernare». L'accento cade sulla prima: HY-ber-nayt. È la parola principale di questo colloquio, quindi pronunciala con sicurezza.

Domande frequenti

Devo conoscere Hibernate se uso Spring Data JPA?

Sì. Spring Data JPA nasconde gran parte del codice, ma il persistence context, il lazy loading e il problema N+1 valgono comunque. Chi intervista chiede spesso del comportamento di Hibernate usando esempi con i repository.

Devo restituire direttamente le entity nelle risposte REST?

Di solito è meglio restituire dei DTO. Le entity possono esporre campi che non vuoi condividere, scatenare il lazy loading durante la serializzazione e legare la tua API al modello del database. Di' che mappi le entity in DTO al confine del servizio.

Come descrivo un problema di prestazioni dell'ORM che ho risolto?

Usa una breve storia: il sintomo, come una pagina lenta, come hai contato le query, la modifica che hai fatto, per esempio un fetch join, e il risultato. Porta un numero che hai davvero misurato, come il conteggio delle query prima e dopo.

Leggere una risposta non è la stessa cosa che dirla. Esercita ogni domanda ad alta voce, poi confronta il significato e la lingua della tua risposta.

Prova SpeakRole ↗

Altri argomenti in quest’area