HIBERNATE'S HIDDEN TRAP: EAGER VS LAZY LOADING (PART 1) 🛌⚡ In Hibernate, there are two ways to load data, and both of them can kill your performance if you aren't careful. 1. THE EAGER TRAP 🍔 Eager loading is "greedy." It fetches the parent and all related children in one go. Sounds efficient? Until you realize that fetching one User just triggered a massive chain reaction that loaded 500 Orders, 2000 Items, and 5000 Reviews into memory. Your "simple" query just became a memory bomb. 2. THE LAZY TRAP 💤 Lazy loading is "procrastinating." it only fetches the children when you actually ask for them. But if you ask for them inside a loop, you trigger the N+1 problem. One query to fetch the list, and then 100 more queries to fetch the details. 3. THE "DETACHED ENTITY" CRASH 💥 We’ve all seen the LazyInitializationException. This happens when you try to access lazy data after the DB transaction has closed. It’s Hibernate’s way of saying, "You should have asked for this earlier!" In Part 2, I’ll show you how to use Join Fetching to get the best of both worlds. #Hibernate #Java #ORM #DatabasePerformance #BackendDevelopment #SoftwareEngineering #JavaPersistenceAPI #DatabaseDesign #PerformanceTuning #TechTips #CodingLife #SoftwareArchitecture #API #SQL
Hibernate Eager vs Lazy Loading Performance Issues
More Relevant Posts
-
Lazy vs Eager Loading — The N+1 Problem Every Java Dev Must Know One of the most common performance killers in Spring Data JPA is the infamous N+1 query problem — and it all starts with how you configure your fetch strategy. By default, @OneToMany and @ManyToMany use LAZY loading — related data is fetched only when accessed. Meanwhile, @ManyToOne and @OneToOne default to EAGER — data is loaded immediately with the parent. The trap? When you load a list of 100 customers and then access their orders in a loop: List<Customer> customers = customerRepo.findAll(); // 1 query for (Customer c : customers) { c.getOrders().size(); // 100 more queries! } // Total: 101 SQL queries = performance disaster Solutions that actually work: // 1. JOIN FETCH in JPQL @Query("SELECT c FROM Customer c JOIN FETCH c.orders") List<Customer> findAllWithOrders(); // 2. @EntityGraph @EntityGraph(attributePaths = {"orders"}) List<Customer> findAll(); Rule of thumb: ✅ Keep FetchType.LAZY as default ✅ Use JOIN FETCH or @EntityGraph when you know you need related data ✅ Enable Hibernate SQL logging to detect N+1 early ❌ Never switch everything to EAGER — that's trading N+1 for over-fetching #Java #SpringBoot #BackendDevelopment #SpringDataJPA #Performance #LearningInPublic
To view or add a comment, sign in
-
-
After getting comfortable with Spring Data JPA and understanding what Hibernate was doing behind the scenes, I thought I had things figured out. 🤔 Then I tried Spring JDBC. Honestly, it felt like going backwards at first. 😅 No repositories. No auto-generated queries. Just plain SQL staring back at me. 📄 I remember writing a simple query and thinking, “Wait… that’s it?” 😶 No hidden joins. No extra queries. No surprises. 🚫 That’s when it started to make sense: With JDBC, what you write is exactly what runs ⚙️ No abstraction means no guessing but also no shortcuts ⚠️ You’re responsible for mapping, queries and performance 🧠 It’s simple… but not easy at scale 📈 At the same time, I started thinking about when to use each: If I need to build features quickly → I reach for JPA 💫 If I’m debugging performance issues → I look at Hibernate 🔄 If I need full control over queries → I go with JDBC 🎯 It made me realize something important: Different tools solve different problems, not everything needs abstraction. #SpringBoot #SpringDataJPA #Hibernate #SpringJDBC #Java #BackendDevelopment #SoftwareEngineering #Database #TechLearning #DeveloperJourney
To view or add a comment, sign in
-
✨ #Day13 – Hibernate: get() vs load() 🔥 Today I explored an important concept in Hibernate (ORM) – the difference between get() and load() 🚀 🔹 Understanding the Core Difference 🤔 👉 get() ✔ Hits the database immediately ✔ Returns actual object ✔ If data not found → returns null 👉 load() ✔ Does NOT hit DB immediately ✔ Returns a proxy object (lazy loading) ✔ DB hit happens only when data is accessed ✔ If data not found → throws Exception 🔹 Example 🧑💻 Student s1 = session.get(Student.class, 1); // DB hit happens here immediately Student s2 = session.load(Student.class, 1); // No DB hit yet s2.getName(); // Now DB hit happens 🔹 Key Differences 📊 ✔ get() → Safe & direct ✔ load() → Faster & lazy ✔ get() → Use when you're not sure data exists ✔ load() → Use when you're sure data exists 🎯 Quick Trick to Remember 👉 get() = Direct DB hit + null if not found 👉 load() = Lazy + exception if not found 🔥 Takeaway Understanding when Hibernate hits the database helps in writing efficient and optimized backend code 💻 #Java #Hibernate #FullStackDeveloper #BackendDevelopment #LearningJourney #Day13 🚀 Anand Kumar Buddarapu,Saketh Kallepu,Uppugundla Sairam
To view or add a comment, sign in
-
-
While debugging a Hibernate issue recently, I came across something interesting 👇 `org.hibernate.ObjectNotFoundException` — a small error with a big lesson. At first glance, it looked like a typical lazy loading problem. But the actual root cause was deeper. 🔍 What was happening? Hibernate created a proxy for a related entity, but when it tried to initialize it, the corresponding row didn’t exist in the database. 👉 In short: The application assumed data integrity, but the database told a different story. ⚠️ The tricky part? The exception wasn’t thrown during query execution. It appeared during debugging when `toString()` was triggered on a proxy object. 💡 Key learnings from this: 🔹 ORM frameworks don’t guarantee data consistency — your database does 🔹 Lazy loading can hide issues until runtime (or even debug time) 🔹 Using Lombok `@ToString` blindly on entities can backfire 🔹 Circular relationships (OneToMany ↔ ManyToOne) can lead to unexpected behavior 🛠 What helped fix it: ✔ Verifying referential integrity at the database level ✔ Avoiding unnecessary eager access during debugging ✔ Restricting `toString()` to only essential fields ✔ Using LEFT JOIN fetch where relationships may be optional 🚀 Takeaway: Most production issues are not about complex logic — they are about mismatches between your assumptions and actual data. Always trust your database more than your ORM. #Java #Hibernate #SpringBoot #BackendDevelopment #Debugging #SoftwareEngineering #Production #ProductionIssues #ErrorHandling
To view or add a comment, sign in
-
🚀 Avoiding the N+1 Problem in Spring Boot (Hibernate) The N+1 problem is a common performance issue where: 👉 1 query fetches parent data 👉 N additional queries fetch related child data 💡 Why does this happen? Because of Lazy Loading (FetchType.LAZY) — Hibernate loads related data only when accessed 📌 Mapping Behavior Matters 🔹 @OneToMany - Default: LAZY 🚨 (Most common cause of N+1) - Accessing children inside a loop triggers multiple queries 🔹 @ManyToOne - Default: EAGER - Usually avoids N+1 - ⚠️ Can lead to unnecessary data fetching 🔹 @OneToOne - Default: EAGER - Safe by default - ⚠️ If changed to LAZY → can cause N+1 📍 Example Scenario - Entity1 → has relation with Entity2 - Fetch list of Entity1 - Access Entity2 inside a loop ⚠️ Hibernate executes: 1 query for Entity1 + N queries for Entity2 → N+1 problem ❌ ✅ Solution: Use JOIN FETCH Example: SELECT e1 FROM Entity1 e1 JOIN FETCH e1.entity2 ✔ Loads both entities in a single query ✔ Eliminates multiple database calls ✔ Improves performance significantly ⚠️ Be careful with @OneToMany - Can produce duplicate parent records due to JOINs - May load large datasets into memory - Use DISTINCT to avoid duplicates - Prefer pagination for large data 🎯 Best Practice 👉 Prefer LAZY loading for flexibility 👉 Use JOIN FETCH when related data is required 👉 Avoid blindly relying on EAGER loading 🔥 Key Takeaway Understanding fetch strategies + entity mappings = Better performance 🚀 #SpringBoot #Hibernate #JPA #Java #Performance #Backend #Optimization #joinfetch
To view or add a comment, sign in
-
Yesterday we talked about how Lombok can crash your app through Hibernate relationships. Today, let’s talk about the other silent killer in those exact same entities: The N+1 Query Problem. If you work with Spring Data JPA long enough, you will eventually write a piece of code that looks completely fine, passes all unit tests, and then completely chokes your database in production. Usually, the culprit is the N+1 problem. The Trap: Let’s say you have a User entity with a @OneToMany relationship to Order. You want to fetch 100 users and print their order totals. You write a simple repository call: userRepository.findAll() (This is 1 query).Then, you loop through those 100 users and call user.getOrders(). What you think happens: Hibernate fetches the users and their orders efficiently. What actually happens: Because relationships are (and should be!) FetchType.LAZY by default, Hibernate executes 1 query to get the 100 users, and then 100 additional queries—one for each user—to fetch their orders. You just hit your database 101 times for a single API request. Multiply that by 1,000 concurrent users, and your DBA is calling you in a panic. 😅 The Senior Fixes: 1. The Quick Fix: JOIN FETCH Instead of using standard findAll(), write a custom JPQL query: SELECT u FROM User u JOIN FETCH u.orders This forces Hibernate to grab everything in a single, efficient JOIN query. 2. The Elegant Fix: @EntityGraph If you don't want to write custom queries, Spring Boot lets you use Entity Graphs to dynamically define which lazy associations should be fetched eagerly for a specific method call. 3. The Ultimate Fix: DTO Projections Stop fetching full Managed Entities if you just need to read data! Write a query that maps directly to a Record or DTO. It bypasses the Hibernate proxy lifecycle entirely and is blazing fast. JPA makes the easy things trivial, but it makes the hard things incredibly dangerous if you don't look at the generated SQL. What is your team's standard way of catching N+1 queries before they hit production? Do you use a specific tool, or rely on code reviews? 👇 #Java #SpringBoot #Hibernate #BackendDevelopment #Microservices #SoftwareEngineering #PerformanceTuning #CleanCode
To view or add a comment, sign in
-
🚀 Understanding the N+1 Query Problem in Spring Boot (With Real Logs) The N+1 query problem is one of the most common performance issues in Spring Data JPA & Hibernate — and it often goes unnoticed until applications hit production scale. To make this concept crystal clear, I built a small Spring Boot demo project that: ✅ Reproduces the N+1 problem using @OneToMany(fetch = LAZY) ✅ Shows how it actually looks in Hibernate SQL logs ✅ Fixes the issue cleanly using EntityGraph (no EAGER fetch) ✅ Uses DTOs to avoid serialization and recursion issues ✅ Keeps the code simple, readable, and interview‑friendly 📌 The goal of this repository is learning + clarity — not just theory, but real behavior and real fixes. 🔗 GitHub Repository: 👉 https://lnkd.in/gDfsT-gu If you’re working with Spring Boot, JPA, or Hibernate, or preparing for interviews, this might be useful. Would love to hear thoughts or alternative approaches you’ve used to handle N+1 👇 #Java #SpringBoot #Hibernate #JPA #BackendDevelopment #Performance #SoftwareEngineering #Learning
To view or add a comment, sign in
-
My code was right. Hibernate disagreed. Last week, while building my side project, I hit a bug that had no error. No exception. No stack trace. Just... missing data. The flow looked clean — Save the bio profile. Then mark the user as bio-completed. Two saves. Straightforward. But every time I ran it, the bio data was getting wiped silently. Hibernate wasn't complaining. It was just quietly overwriting what I'd saved — because currentUser was loaded before the bio was written. Its in-memory state was stale. And when I called userRepository.save(currentUser), Hibernate trusted that stale object completely and flushed it back to the database. Classic entity state pollution. Silent. No warnings. The minimal fix would've been reordering the saves. I didn't go with that. Instead I wrote a surgical JPQL update — touching only the one column I needed to change. No entity graph. No dirty checking. No surprises. Hibernate is powerful. But it trusts your object state completely. If your object is stale, your database pays the price — quietly. If you're calling multiple repository.save() in one flow, ask yourself: "Does any of these entities hold a stale reference to something the other just wrote?" It's a question worth asking before Hibernate answers it for you. #Java #SpringBoot #SoftwareEngineering
To view or add a comment, sign in
-
-
🚀43/100 - N+1 Problem in Hibernate If you’re working with JPA/Hibernate, you are likely facing this without realizing it. What is N+1 Problem 🔸1 query to fetch parent data (Department) 🔸N queries to fetch child data (Employees) 🔸Total → N + 1 queries 🔸Fetching 5 departments → triggers 6 queries Why does this happen 🔸Root cause = Lazy Loading 🔸Hibernate does NOT fetch related data initially 🔸It loads a proxy (placeholder) 🔸When accessed → fires a query 🔸Access inside loop → multiple queries → N+1 Where it usually happens 🔹OneToMany relationships 🔹Looping over entities 🔹Returning entities directly in APIs 🔹Nested object access Why this is a problem 🔸Multiple DB hits → performance degradation 🔸Increased latency 🔸Heavy load on database 🔸Not scalable for large datasets How to solve this Spring Boot Approach (Recommended) 🔸@EntityGraph(attributePaths = "employees") 🔸Forces single query fetch Hibernate / JPQL Approach 🔸JOIN FETCH Example: SELECT d FROM Department d JOIN FETCH d.employees Other Approaches 🔸DTO Projection → fetch only req data 🔸Batch Fetching → reduces queries 🔸Avoid blind EAGER loading Key takeaway 🔹Lazy loading is not bad 🔹Lazy loading + loop = N+1 problem 🔹Always control how data is fetched I’ve created a complete backend developer guide covering: 🔸What is N+1 problem (with examples) 🔸Why it happens (deep dive - lazy loading) 🔸Real code (Entity, Repo,Service,Controller) 🔸With vs Without N+1 execution 🔸EntityGraph vs Fetch Join 🔸Multiple optimization approaches 🔸Diagrams for clear understanding Worth going through if you're preparing for backend interviews or building scalable APIs. Save & Repost🔁 if this helps someone preparing seriously Follow Surya Mahesh Kolisetty for more backend and Java deep dives #Java #SpringBoot #Hibernate #BackendDevelopment #JPA #SystemDesign #Performance #InterviewPreparation #SoftwareEngineering #CodingInterview #Developers #TechLearning #CFBR #SystemDesign #MicroServices
To view or add a comment, sign in
-
🚀 Evolution of Database Interaction in Java (🔧➡️⚙️➡️🚀) It’s fascinating how the “most natural way” to work with databases has evolved over time 👇 🔹 JDBC You write everything manually—queries, connections, result parsing. Full control, but a lot of boilerplate. 🔹 Hibernate ORM We move to object mapping. Less SQL, more Java objects. Cleaner, but still requires configuration and understanding ORM behavior. 🔹 Spring Boot with JPA Things get easier. Auto-configuration, reduced setup, better integration. Focus shifts more toward business logic. 🔹 Spring Data JPA (Repository methods) 🤯 Now this feels like magic! Define methods → Framework generates queries → Minimal SQL needed. 👉 From writing complex SQL to just defining method names… we’ve come a long way. 💡 But here’s the reality: Every layer matters. Understanding JDBC and SQL makes you a stronger developer—even when using high-level abstractions. 📌 Abstraction reduces effort, but fundamentals build mastery. What’s your preferred way of interacting with databases? 👇 #Java #SpringBoot #JPA #Hibernate #BackendDevelopment #SoftwareEngineering #LearningJourney
To view or add a comment, sign in
-
Explore content categories
- Career
- Productivity
- Finance
- Soft Skills & Emotional Intelligence
- Project Management
- Education
- Technology
- Leadership
- Ecommerce
- User Experience
- Recruitment & HR
- Customer Experience
- Real Estate
- Marketing
- Sales
- Retail & Merchandising
- Science
- Supply Chain Management
- Future Of Work
- Consulting
- Writing
- Economics
- Artificial Intelligence
- Employee Experience
- Workplace Trends
- Fundraising
- Networking
- Corporate Social Responsibility
- Negotiation
- Communication
- Engineering
- Hospitality & Tourism
- Business Strategy
- Change Management
- Organizational Culture
- Design
- Innovation
- Event Planning
- Training & Development
Detect this kind of issues https://joptimize.io