Aabhas Jain’s Post

💡 Day 3 of my 𝗝𝗮𝘃𝗮 𝗕𝗮𝗰𝗸𝗲𝗻𝗱 𝗤𝘂𝗲𝘀𝘁𝗶𝗼𝗻 𝗼𝗳 𝘁𝗵𝗲 𝗗𝗮𝘆 𝘀𝗲𝗿𝗶𝗲𝘀: 🧠 Question: You’re working on a Spring Boot application that interacts with a relational database. You notice that for every request, multiple queries are executed for fetching related entities - causing performance issues. 👉 What is the N+1 query problem in JPA/Hibernate, and how can you avoid it? ✅ Answer: The N+1 query problem happens when Hibernate fires: 1 query to fetch parent records N queries to fetch child records for each parent This results in N+1 queries, hurting performance. To avoid it: > Use fetch join 𝘚𝘌𝘓𝘌𝘊𝘛 𝘶 𝘍𝘙𝘖𝘔 𝘜𝘴𝘦𝘳 𝘶 𝘑𝘖𝘐𝘕 𝘍𝘌𝘛𝘊𝘏 𝘶.𝘰𝘳𝘥𝘦𝘳𝘴 > Use @EntityGraph to pre-fetch relationships > Enable batch fetching 𝘩𝘪𝘣𝘦𝘳𝘯𝘢𝘵𝘦.𝘥𝘦𝘧𝘢𝘶𝘭𝘵_𝘣𝘢𝘵𝘤𝘩_𝘧𝘦𝘵𝘤𝘩_𝘴𝘪𝘻𝘦=20 > Always monitor SQL logs to detect hidden N+1 issues. ✅ Fetch joins, entity graphs, and batch fetching = faster DB access & fewer queries ⚡ See you tomorrow for Day 4 👋 #Java #SpringBoot #Hibernate #JPA #Performance #BackendDeveloper #ContinuousLearning #QuestionOfTheDay

To view or add a comment, sign in

Explore content categories