Avoiding N+1 Queries in Spring Boot with EntityGraph and Formula

🚨 𝗬𝗼𝘂𝗿 𝗦𝗽𝗿𝗶𝗻𝗴 𝗕𝗼𝗼𝘁 𝗔𝗽𝗽 𝗜𝘀 𝗤𝘂𝗶𝗲𝘁𝗹𝘆 𝗕𝘂𝗿𝗻𝗶𝗻𝗴 𝗤𝘂𝗲𝗿𝗶𝗲𝘀 🤯 Most developers use @𝗙𝗼𝗿𝗺𝘂𝗹𝗮 and @𝗘𝗻𝘁𝗶𝘁𝘆𝗚𝗿𝗮𝗽𝗵 interchangeably. That one mistake can turn a 1-query operation into 1,001. 𝗪𝗵𝗮𝘁'𝘀 𝗮𝗰𝘁𝘂𝗮𝗹𝗹𝘆 𝗵𝗮𝗽𝗽𝗲𝗻𝗶𝗻𝗴 𝘂𝗻𝗱𝗲𝗿 𝘁𝗵𝗲 𝗵𝗼𝗼𝗱? @Formula looks innocent: @𝙁𝙤𝙧𝙢𝙪𝙡𝙖("(𝙎𝙀𝙇𝙀𝘾𝙏 𝘾𝙊𝙐𝙉𝙏(*) 𝙁𝙍𝙊𝙈 𝙤𝙧𝙙𝙚𝙧𝙨 𝙤 𝙒𝙃𝙀𝙍𝙀 𝙤.𝙘𝙪𝙨𝙩𝙤𝙢𝙚𝙧_𝙞𝙙 = 𝙞𝙙)") 𝙥𝙧𝙞𝙫𝙖𝙩𝙚 𝙇𝙤𝙣𝙜 𝙤𝙧𝙙𝙚𝙧𝘾𝙤𝙪𝙣𝙩; But Hibernate fires a separate subquery for every row fetched. 500 customers → 500 extra DB hits. That's the 𝗡+𝟭 problem wearing a clean disguise. @𝗘𝗻𝘁𝗶𝘁𝘆𝗚𝗿𝗮𝗽𝗵 𝗱𝗼𝗲𝘀 𝗶𝘁 𝗿𝗶𝗴𝗵𝘁: @𝙀𝙣𝙩𝙞𝙩𝙮𝙂𝙧𝙖𝙥𝙝(𝙖𝙩𝙩𝙧𝙞𝙗𝙪𝙩𝙚𝙋𝙖𝙩𝙝𝙨 = {"𝙤𝙧𝙙𝙚𝙧𝙨", "𝙖𝙙𝙙𝙧𝙚𝙨𝙨"}) 𝙇𝙞𝙨𝙩<𝘾𝙪𝙨𝙩𝙤𝙢𝙚𝙧> 𝙛𝙞𝙣𝙙𝘼𝙡𝙡𝙒𝙞𝙩𝙝𝙊𝙧𝙙𝙚𝙧𝙨(); One JOIN. All related data. Done. The real-world gap Same 500 products, with category + supplier associations: ❌ Wrong fetch strategy → 1,001 queries ✅ @EntityGraph → 1 query Same data. P99 latency going from 80ms to 4 seconds. In production. 𝗪𝗵𝗲𝗻 𝘁𝗼 𝘂𝘀𝗲 𝘄𝗵𝗶𝗰𝗵  • ScenarioUseComputed value (count, sum) ->@Formula  • Fetching related entities -> @EntityGraph  • Sort/filter by derived column -> @Formula  • Avoiding lazy loading on APIs -> @EntityGraph One question cuts through the confusion every time: "Am I computing something, or loading something?" They're not competing tools — they solve different problems. The mistake is reaching for @𝗙𝗼𝗿𝗺𝘂𝗹𝗮 where a JOIN belongs. Most Spring Boot performance issues I've seen weren't bad logic. They were the wrong fetch strategy in the right place. Have you hit this in production? Drop it in the comments 👇 #Java #SpringBoot #Programming #SoftwareEngineering #SoftwareDevelopment #JPA #Hibernate #BackendDevelopment #BackendEngineering #APIDesign #SystemDesign #PerformanceOptimization #CleanCode #CodeQuality #TechDebt #TechCommunity #100DaysOfCode #LearnToCode #Developer #CodingLife

  • diagram

Exactly, Neeraj! Such small mistakes in choosing the right approach often leads to DB crash down and server failures!!

To view or add a comment, sign in

Explore content categories