VWhat is the N+1 problem in JPA, and how do you avoid it?
Mülakat sorusuHibernate / JPA
JPA bir spesifikasyondur, Hibernate ise en yaygın gerçeklemesidir (implementation). Mülakatçılar persistence context'i, SQL'in gerçekte ne zaman gönderildiğini ve dikkatsiz kullanıldığında bir ORM'in performansa nasıl zarar verebileceğini anladığınızı duymak ister.
Sözlü bir cevap için güvenilir bir yapı şudur: özelliğin ne yaptığı, gerçek bir serviste yaratabileceği sorun ve bunu nasıl düzelttiğiniz ya da önlediğiniz. Kısa bir örnek kullanın; örneğin kalemlerden oluşan bir listeye sahip bir sipariş, çünkü somut bir resmi yüksek sesle anlatmak daha kolaydır.
- ✓Kelimeler → ifadeler → cümleler → konuşma
- ✓Yanıtın anlamı
- ✓Dil
Sık sorulan mülakat soruları ve örnek cevaplar
What is the persistence context, and what states can an entity have?
Persistence context nedir ve bir entity hangi durumlarda olabilir?
Mülakatçı ne duymak ister. Birinci seviye önbellek ve iş birimi (unit of work) olarak persistence context, dört durum ve dirty checking'in ne demek olduğu.
Yüksek sesle çalışmak için İngilizce örnek cevapThe 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?
Lazy ile eager loading arasındaki fark nedir ve LazyInitializationException nedir?
Mülakatçı ne duymak ister. Varsayılan fetch türleri, proxy'ler ve mantıklı bir çözüm. İyi bir cevap her şeyi eager yapmakla yetinmez.
Yüksek sesle çalışmak için İngilizce örnek cevapWith 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?
N+1 sorunu nedir ve nasıl çözersiniz?
Mülakatçı ne duymak ister. Net bir örnek, SQL logları ya da sorgu sayısıyla nasıl tespit edileceği ve bir uyarıyla birlikte birden fazla çözüm.
Yüksek sesle çalışmak için İngilizce örnek cevapThe 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?
Aynı entity üzerindeki eşzamanlı güncellemeleri nasıl yönetirsiniz?
Mülakatçı ne duymak ister. İyimser (optimistic) ve kötümser (pessimistic) kilitleme, her birinin ne zaman uygun olduğu ve kısa transaction'lar.
Yüksek sesle çalışmak için İngilizce örnek cevapI 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?
Hibernate'te önbellekleme nasıl çalışır?
Mülakatçı ne duymak ister. Birinci ve ikinci seviye önbellek, ikinci seviyenin isteğe bağlı olduğu bilgisi ve eskimiş veri riski.
Yüksek sesle çalışmak için İngilizce örnek cevapThere 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.
Anahtar terimler nasıl telaffuz edilir
- Hibernate
- HAY-bır-neyt
- entity
- EN-ti-ti
- JPA
- cey-pi-ey
- ORM
- o-ar-em
- lazy
- LEY-zi
- detached
- di-TEÇT
- cascade
- kes-KEYD
Cevap vermek için kullanışlı kalıplar
- At flush time, Hibernate…Flush anında Hibernate…
- The entity is managed, so the change is tracked.Entity managed durumda olduğu için değişiklik izleniyor.
- I would check the generated SQL first.Önce üretilen SQL'e bakardım.
- The number of queries grows with the number of rows.Sorgu sayısı, satır sayısıyla birlikte artıyor.
- I load exactly what the use case needs.Kullanım senaryosunun tam olarak ihtiyaç duyduğunu yüklerim.
- The trade-off is convenience against control.Ödünleşim (trade-off), kolaylık ile kontrol arasında.
- I would measure before I enable a cache.Önbelleği açmadan önce ölçerdim.
Sık yapılan hatalar
- ORM'e "yavaş" demek. Tam olarak neyin yavaş olduğunu söyleyin: çok fazla sorgu, çok fazla veri yüklenmesi ya da uzun transaction'lar. Sonra bunu nasıl bulduğunuzu anlatın.
- Her lazy loading hatasını eager loading'e geçerek çözmek. Bu, sorunu gizler ve gerekenden fazla veri yükler.
- JPA ile Hibernate'i karıştırmak. JPA standart API'dir; Hibernate ise ek özellikleri olan bir gerçeklemedir. Bir özelliğin hangisine ait olduğunu söyleyin.
- save metodunun veritabanına anında yazdığını söylemek. Hibernate SQL'i flush ya da commit anına kadar erteleyebilir; izlenen bir değişiklik ile gerçek SQL ifadesi arasındaki farkı açıklayın.
- "Hibernate" sözcüğünde yanlış heceyi vurgulamak; örneğin “hi-ber-NEYT” demek. Vurgu ilk hecededir: HAY-bır-neyt. Bu, mülakatın ana sözcüğü; bu yüzden güvenle söyleyin.
Sıkça sorulan sorular
Spring Data JPA kullanıyorsam Hibernate bilmem gerekir mi?
Evet. Spring Data JPA kodun büyük kısmını gizler ama persistence context, lazy loading ve N+1 sorunu yine geçerlidir. Mülakatçılar Hibernate davranışını çoğu zaman repository örnekleri üzerinden sorar.
REST yanıtlarında entity'leri doğrudan döndürmeli miyim?
Genellikle DTO döndürmek daha iyidir. Entity'ler paylaşmak istemediğiniz alanları açığa çıkarabilir, serileştirme sırasında lazy loading'i tetikleyebilir ve API'nizi veritabanı modelinize bağlar. Entity'leri servis sınırında DTO'ya çevirdiğinizi söyleyin.
Çözdüğüm bir ORM performans sorununu nasıl anlatırım?
Kısa bir hikâye kullanın: belirti (örneğin yavaş bir sayfa), sorguları nasıl saydığınız, yaptığınız değişiklik (örneğin bir fetch join) ve sonuç. Gerçekten ölçtüğünüz bir rakam verin; değişiklikten önceki ve sonraki sorgu sayısı gibi.
Bir cevabı okumak ile onu söylemek aynı şey değildir. Her soruyu yüksek sesle çalışın, ardından kendi cevabınızın anlamını ve dilini karşılaştırın.
SpeakRole’i dene ↗Bu alandaki diğer konular