💡 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
Aabhas Jain’s Post
More Relevant Posts
-
🚀 Day 20 — ORM vs JDBC, JPA Explained & Complete Hibernate CRUD! Today I deepened my backend skills by understanding how data persistence works in real enterprise applications. 🔗 JDBC vs ORM (Hibernate) JDBC: Low-level, verbose, manual handling of SQL, mapping, and resources. ORM (Hibernate): Maps Java objects to database tables automatically, reduces boilerplate, and improves maintainability. 🧠 JPA in Simple Terms JPA is a specification (rules). Hibernate is an implementation (actual working framework). It handles: ✅ ORM ✅ Entity lifecycle ✅ Transactions ✅ Query abstractions 🛠️ What I built today: ✅ hibernate.cfg.xml configuration ✅ Entity classes with annotations ✅ Full CRUD operations (Create, Read, Update, Delete) ✅ Understood generated SQL behind the scenes 💡 Key Takeaways Entities map directly to database tables Hibernate frees you from repetitive SQL Cleaner, scalable backend code Huge thanks to Faisal Memon sir for the guidance and clear explanations throughout this learning path. 🙌 #Java #Hibernate #JPA #ORM #BackendDevelopment #LearningJourney #Day20
To view or add a comment, sign in
-
Avoiding JPA/Hibernate Pitfalls and Implementing Fixes 🧰 - To tackle N+1 queries, opt for fetch joins or entity graphs over separate queries. 🕸️ - Refrain from lazy-loading in controllers; instead, map to DTOs within the service layer. 🧭 - For bypassing the 1st-level cache during bulk updates, ensure to clear the context. 🧹 - Address hot rows by incorporating @Version for optimistic locking. 🔒 - When dealing with paging, prioritize stable sorting, accurate counting, and steer clear of fetch-join operations during pagination. 📑 - Enhance performance with batch inserts by configuring hibernate.jdbc.batch_size and executing flush/clear operations. 📦 - Implement auditing using Envers or explicit outbox tables. 🧾 - Profiling SQL queries is essential; avoid blind optimization strategies. 🔎 Remember, always stay vigilant and proactive in your SQL profiling efforts for optimal performance. #JPA #Hibernate #SpringData #SQL #Java
To view or add a comment, sign in
-
Hibernate’s N+1 Problem — The Silent Performance Killer 😱 If your app feels slow even with small data — you might be a victim of the N+1 SELECT Problem in Hibernate 🐢 --- 🧩 What is the N+1 Problem? Imagine this 👇 You fetch all Departments (1 query), and for each department, Hibernate fires another query to get its Employees (N queries). ➡️ Total = N + 1 queries! 😬 List<Department> departments = session.createQuery("from Department", Department.class).list(); for (Department dept : departments) { System.out.println(dept.getEmployees().size()); } 💥 Result: 1 query for Departments + N queries for Employees = Performance Disaster! --- ⚡ The Fix — Use JOIN FETCH Tell Hibernate to fetch related data in a single query 🧠 List<Department> departments = session .createQuery("SELECT d FROM Department d JOIN FETCH d.employees", Department.class) .list(); ✅ Result: Only 1 query to fetch everything 🚀 --- 🧠 Pro Tips to Avoid N+1 Traps: 💡 Use @EntityGraph for flexible fetch strategies 💡 Avoid global EAGER fetching — it often backfires 💡 Enable show_sql or use p6spy to monitor queries --- 🔥 Remember: Small query issues today become big performance nightmares tomorrow. 💬 Have you ever battled the N+1 monster in production? How did you fix it? #Hibernate #SpringBoot #Java #JPA #BackendDevelopment #Performance #CodeOptimization #Microservices #Developers
To view or add a comment, sign in
-
Java Performance Tip 🚀 Dealing with large datasets in Spring Data JPA? Stop loading everything into memory! Use Stream-based queries with proper fetch size configuration for better memory management and performance. ✅ Old way: Loads entire result set into memory - potential OutOfMemoryError ✅ New way: Streams data in batches - efficient memory usage and better performance Key Benefits: 🎯 Prevents OutOfMemoryError with large datasets ⚡ Processes data in chunks (batch of 1000 records) 💾 Lower memory footprint 🔄 Works seamlessly with Java Streams API 📊 Perfect for data processing and reporting Pro Tips: Always close streams properly (use try-with-resources) Use @Transactional(readOnly = true) on service methods #Java #SpringBoot #SpringData #JPA #Hibernate #Performance #BestPractices #CleanCode #SoftwareDevelopment #BackendDevelopment #TechTips
To view or add a comment, sign in
-
-
⚡ Speed Up Your JPA Reads with @QueryHints Last week, I was investigating why one of our dashboards was slow, even though the query behind it was just fetching data. No complex joins, no massive tables — just plain JPA reads. But every time the method ran, Hibernate seemed to be doing more work than necessary. 🤨 Turns out… it was performing dirty checks on all retrieved entities — even though the data was never being updated! That’s when I came across a little gem: @QueryHints. 💡 With one small annotation, you can tell Hibernate that a query is read-only, and it can safely skip the extra bookkeeping. 💡 Here’s how: @QueryHints(@QueryHint(name = org.hibernate.annotations.QueryHints.READ_ONLY, value = "true")) @Query("SELECT u FROM User u") List<User> findAllUsers(); Or globally for a transaction: @Transactional(readOnly = true) public List<User> getAllUsers() { return userRepository.findAll(); } After adding that one line, the unnecessary dirty checks disappeared, and the query execution became much faster — especially noticeable on large result sets. Sometimes, performance isn’t about changing the database — it’s about telling your ORM what not to do. 😄 #Hibernate #SpringBoot #JPA #Java #Performance #BackendDevelopment #Microservices #CodingTips
To view or add a comment, sign in
-
-
🔥 JDBC Made Simple: My Notes (so your database queries don’t fail 😅) Hey LinkedIn 👋 After mastering Core & Advanced Java and brushing up on Maven, I dived into JDBC — the bridge between Java and databases. Here’s a concise snapshot of what I learned and why it matters for real-world projects. 🚀 📚 What I covered Statement vs PreparedStatement — PreparedStatement makes queries safe, clean, and efficient; avoids messy string concatenation and SQL injection. Insert, Update, Delete — dynamic SQL with placeholders (?) and methods like setInt, setString for passing variables. CallableStatement — execute stored procedures from Java with input/output parameters. Why PreparedStatement matters — precompiled queries improve performance and caching; always use it for dynamic data. Practical JDBC workflow — connect, prepare query, set parameters, execute, close resources. 🧩 Why it matters? Prevents SQL injection and ensures data integrity. Makes database operations clean, readable, and maintainable. Supports dynamic operations: insert, update, delete, and select with minimal boilerplate. Prepares you to work with real-world applications and enterprise databases. ✅ Practical takeaway: Always use PreparedStatement for queries with dynamic data. Use CallableStatement for stored procedures only. Replace all ? placeholders, or your query will fail. Close resources after execution to avoid connection leaks. Attached the notes below for your reference 👇 🚀 What’s Coming Next? Part 4 of my journey: ✅ Hibernate ✅ Full Spring Ecosystem: • Spring Boot | MVC | JSP | Servlets • Spring Data JPA | AOP | REST APIs • Spring Security | JWT | OAuth2 • Microservices | Docker #JDBC #Java #Database #PreparedStatement #CallableStatement #SpringBoot #Microservices #SoftwareEngineering #DeveloperCommunity #LearningInPublic #DevJourney #Programming
To view or add a comment, sign in
-
Understanding @Modifying Annotation in Spring Data JPA By default, JPA queries are read-only. But what if you need to update or delete data using a custom query? That’s where the @Modifying annotation comes in. Key points: > Use @Modifying with @Query to execute INSERT, UPDATE, or DELETE operations. > Return type can be int or void. > Must be used inside a transaction (@Transactional), otherwise changes won’t persist. 📍Tip: Always be careful these queries skip entity-level lifecycle events and directly modify the database. #SpringBoot #JPA #Hibernate #Java
To view or add a comment, sign in
-
-
The Object-Oriented Way to Query Data If you’ve used JPA or Hibernate, you’ve probably heard of JPQL - the Java Persistence Query Language. It’s like SQL, but instead of querying tables and columns, you query Java objects (entities) and their fields. This makes your queries database-independent and aligned with your domain model. Example :- @Query("SELECT e FROM Employee e WHERE e.department = :dept") List<Employee> findByDepartment(@Param("dept") String department); Here’s what’s happening: Employee is an entity class, not a table name. department is a field in the Employee class, not a column. JPQL automatically translates this into SQL like: SELECT * FROM employees WHERE department = 'IT'; So instead of thinking in terms of tables, you think in terms of objects - much more natural for Java developers. Once you master JPQL, you’ll rarely need to write raw SQL again — and your code stays portable, readable, and easy to maintain. #Java #JPA #Hibernate
To view or add a comment, sign in
-
-
🔑 The Single Line of Code That Saved Our Database I inherited a Spring Boot service that was brutally slow under load. The monitoring graphs looked like jagged mountains. 📈The initial assumption was that the database server was undersized, but the real issue was much closer to home.🏡 The Java application was executing a seemingly innocent query to load a list of related data, but it was using the default Hibernate fetch strategy for a one-to-many relationship. This resulted in the infamous N+1 problem: the service ran one query to get the parent records, and then N separate queries to fetch the children, one for each parent. Suddenly, one user request was hitting the MySQL server 50 times!😱 The fix was a single line of code, switching the fetch type to JOIN or using @Query with a FETCH JOIN. The database load instantly dropped by 90%, and the API response time went from 4 seconds to under 200 milliseconds. 🚀 Never underestimate how silently ORM (Object-Relational Mapping) pitfalls can kill your performance. Have you ever found a massive bottleneck hidden by your ORM? Share your fix!👇 #SpringBoot #MySQL #Java #BackendDevelopment #Performance
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