🚨 𝗬𝗼𝘂𝗿 𝗦𝗽𝗿𝗶𝗻𝗴 𝗕𝗼𝗼𝘁 𝗔𝗽𝗽 𝗜𝘀 𝗤𝘂𝗶𝗲𝘁𝗹𝘆 𝗕𝘂𝗿𝗻𝗶𝗻𝗴 𝗤𝘂𝗲𝗿𝗶𝗲𝘀 🤯 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
Avoiding N+1 Queries in Spring Boot with EntityGraph and Formula
More Relevant Posts
-
Stop putting Lombok’s @Data on your JPA Entities. I know it saves time. You create a new Entity, slap @Data at the top of the class, and instantly get all your getters, setters, and string methods without writing boilerplate. But after 9 years of debugging Spring Boot applications, I can tell you this is one of the most common ways to silently crash your server in production. Here is why Senior Engineers ban @Data on the database layer: 1. The StackOverflowError Trap If you have a bidirectional relationship (like a User entity that has a list of Order entities, and an Order points back to a User), @Data generates a toString() method that calls the toString() of its children. User calls Order, Order calls User, and your app crashes in an infinite loop the second you try to log it. 2. The Performance Killer @Data automatically generates equals() and hashCode(). In Hibernate, evaluating these on lazy-loaded collections can accidentally trigger a massive database query just by adding the entity to a HashSet. You suddenly fetched 10,000 records without writing a single SELECT statement. The Senior Fix: Keep your database entities explicit and predictable. Instead of @Data, just use @Getter and @Setter. If you absolutely need a toString(), write it yourself or use @ToString.Exclude on your relational fields to break the loop. Lombok is an amazing tool, but using it blindly on your entities is a ticking time bomb. Have you ever taken down a dev environment because of an infinite toString() loop? Let's share some war stories below. 👇 #Java #SpringBoot #Hibernate #CleanCode #SoftwareEngineering #BackendDevelopment #LLD #SystemDesign
To view or add a comment, sign in
-
We've been building something quietly for a while, and I'm ready to share it. OpenTaint is an open-source taint analysis engine with the most thorough Spring Boot support. https://lnkd.in/darQ5ZRN Not "Java support." Actual modeling of how Spring works. Spring Boot's annotation-driven architecture creates data flows that are invisible to conventional static analysis. A bean injection crosses class boundaries with no call site in the source. JPA persistence links two HTTP endpoints through the database with no shared code path. A Freemarker configuration object determines whether user input reaching template.process() is exploitable — or harmless. These are not edge cases. This is the default architecture of most Java web applications. OpenTaint traces tainted data through every layer: - Following data across file and class boundaries — through DTO field access and method chains. - Resolving configuration-aware sinks — tracing through DI to determine whether a resolver or handler is actually exploitable. - Connecting endpoints through persistence — where the database or service state is the only link. - Distinguishing dangerous fields from safe ones — at per-column granularity within those flows. The engine operates on bytecode, resolves virtual dispatch, and maps every finding back to its HTTP endpoint. If you're using Semgrep or CodeQL on your Java/Kotlin/Spring codebase — try OpenTaint on the same project and compare what it finds. We've published reproducible comparisons on the blog, but seeing it on your own code is more convincing. Apache 2.0 + MIT. Engine, rules, CLI, GitHub Action, GitLab CI — everything is open source. #java #kotlin #spring #springboot #security #appsec #opensource #sast #taintanalysis
To view or add a comment, sign in
-
-
Is FetchType.EAGER silently killing your performance? 🚨 One mistake I’ve seen repeatedly in Spring Boot applications is overusing EAGER fetching. Looks harmless… until it hits production. The problem 👇 Every time you fetch a parent entity, Hibernate also loads the entire child collection. Now imagine: → A user with 5,000 orders → A department with 50,000 employees Your “simple query” just became a massive memory load. This doesn’t just slow things down… it stresses your entire JVM. What I follow instead 👇 ✔ Default to LAZY ✔ Use JOIN FETCH when needed ✔ Use @EntityGraph for controlled fetching Your entity design is not just structure. It’s a performance decision. Better to write 1 extra query… than load 10,000 unnecessary records. Curious to hear from other devs 👇 Do you treat FetchType.EAGER as a bad practice? Or still use it in some cases? #Java #SpringBoot #JPA #Hibernate #BackendDevelopment #SoftwareEngineering #Performance #TechDiscussion
To view or add a comment, sign in
-
-
🚀 Day 19 – map() vs flatMap() in Java Streams While working with Streams, I came across a subtle but important difference: "map()" vs "flatMap()". --- 👉 map() Transforms each element individually List<String> names = Arrays.asList("java", "spring"); names.stream() .map(String::toUpperCase) .forEach(System.out::println); ✔ Output: JAVA, SPRING --- 👉 flatMap() Flattens nested structures List<List<Integer>> list = Arrays.asList( Arrays.asList(1, 2), Arrays.asList(3, 4) ); list.stream() .flatMap(Collection::stream) .forEach(System.out::println); ✔ Output: 1, 2, 3, 4 --- 💡 Key insight: - "map()" → 1-to-1 transformation - "flatMap()" → 1-to-many (and then flatten) --- ⚠️ Real-world use: "flatMap()" is very useful when dealing with: - Nested collections - API responses - Complex data transformations --- 💡 Takeaway: Understanding when to use "flatMap()" can make your stream operations much cleaner and more powerful. #Java #BackendDevelopment #Java8 #Streams #LearningInPublic
To view or add a comment, sign in
-
𝗛𝗮𝘀𝗵𝗠𝗮𝗽 𝘃𝘀 𝗛𝗮𝘀𝗵𝘁𝗮𝗯𝗹𝗲 — 𝗧𝗵𝗲 𝗕𝗮𝗰𝗸𝗯𝗼𝗻𝗲 𝗼𝗳 𝗝𝗮𝘃𝗮 𝗣𝗲𝗿𝗳𝗼𝗿𝗺𝗮𝗻𝗰𝗲 Every Java developer uses HashMap… but very few truly understand how it works internally. Let’s break it down for more understanding: => What is HashMap? A data structure that stores key-value pairs and provides near O(1) performance using hashing. => How it works internally: 1. Key → hashCode() → bucket index 2. Data stored in an array (buckets) 3. Collision? → LinkedList (Java 7) → Red-Black Tree (Java 8+) => Why it's powerful? Because it avoids full traversal and directly jumps to the correct bucket. => Key Characteristics: 1. Allows one null key 2. Allows multiple null values 3. Not thread-safe => Hashtable (Legacy Structure): 1. Thread-safe (synchronized) ✔️ 2. Slower due to locking ❌ 3. No null keys/values ❌ Difference between HashMap and Hashtable HashMap = Fast + Modern Hashtable = Legacy + Synchronized => Interview Insight: If two keys have the same hashCode but different equals() → They go into the same bucket but remain separate entries. => Pro Tip: Bad hashCode() = Poor performance = System bottleneck => HashMap is not just a collection — it’s the foundation of scalable backend systems. #Java #SystemDesign #CodingInterview #BackendDevelopment #SoftwareEngineering
To view or add a comment, sign in
-
-
🚨 𝗧𝗵𝗲 𝗦𝗶𝗹𝗲𝗻𝘁 𝗣𝗲𝗿𝗳𝗼𝗿𝗺𝗮𝗻𝗰𝗲 𝗞𝗶𝗹𝗹𝗲𝗿 𝗶𝗻 𝗦𝗽𝗿𝗶𝗻𝗴 𝗕𝗼𝗼𝘁 — 𝗡+𝟭 𝗤𝘂𝗲𝗿𝘆 𝗣𝗿𝗼𝗯𝗹𝗲𝗺 Everything works fine… Until your API suddenly becomes slow in production 😅 That’s when many discover the N+1 Query Problem. 𝗪𝗵𝗮𝘁 𝗶𝘀 𝗡+𝟭? You fetch 1 parent entity Then Hibernate runs N additional queries for child entities 👉 Total queries = N + 1 👉 Performance = 📉 𝗘𝘅𝗮𝗺𝗽𝗹𝗲 Fetching Departments with Employees: Instead of 1 query, Hibernate runs: • 𝟭 𝗾𝘂𝗲𝗿𝘆 → Fetch departments • 𝗡 𝗾𝘂𝗲𝗿𝗶𝗲𝘀 → Fetch employees for each department Boom 💥 Performance issue. 𝗖𝗼𝗺𝗺𝗼𝗻 𝗠𝗶𝘀𝘁𝗮𝗸𝗲 A common instinct is to switch to EAGER loading to fix it. But… ❌ EAGER can also cause N+1 ❌ More memory usage ❌ Less control 𝗕𝗲𝘁𝘁𝗲𝗿 𝗦𝗼𝗹𝘂𝘁𝗶𝗼𝗻𝘀 ✅ ✔️ JOIN FETCH Fetch everything in a single query ✔️ EntityGraph Cleaner and more flexible approach ✔️ Batch Size Reduces queries for large datasets ✔️ DTO Projection Best for read-only APIs and performance Understanding this early can save hours of debugging in production 🚀 #connections #SpringBoot #Hibernate #Java #Backend #Performance #JPA #SoftwareEngineering #interviewPrep #interviewQuestion
To view or add a comment, sign in
-
-
🚀 Day 16 – ClassLoaders: Architecture View If JVM is the engine, ClassLoaders are the gatekeepers — responsible for loading every .class into memory exactly when needed. Understanding ClassLoader architecture helps you debug class-not-found issues, memory leaks, shading conflicts, and container-based classpath problems. 🔍 How Class Loading Works JVM uses a hierarchical delegation model: 1️⃣ Bootstrap ClassLoader Loads core Java classes (java.*) Part of the JVM (native) 2️⃣ Extension / Platform ClassLoader Loads classes from $JAVA_HOME/lib/ext or platform modules 3️⃣ Application / System ClassLoader Loads everything from your classpath or app’s JARs ➡️Custom ClassLoaders Used by app servers, frameworks, plugin systems (Tomcat, OSGi, Spring Boot Layers) 🧠 Key Architecture Concepts ✔ Parent Delegation Model Child → Parent first. Prevents overriding core Java classes (security). ✔ Shadowing / Overriding Custom loaders can break delegation intentionally (OSGi, plugin engines). ✔ Namespace Isolation Each ClassLoader has its own namespace — Same class name loaded by two loaders = treated as different classes. ✔ Hot Reloading & Dynamic Loading Custom loaders allow: - Reloading modules - Loading JARs at runtime - Containerized class isolation 🎯 Why Should Developers/Architect Know This? - Fixing ClassNotFoundException, NoClassDefFoundError, LinkageError - Designing microservice modular architecture - Understanding how frameworks like Spring Boot, Quarkus, Tomcat, Jetty,Hadoop manage classes - Optimizing startup time (JVM warmup, classpath scanning) #Java #Microservices #ClassLoaders #JVM #100DaysofJavaArchitecture
To view or add a comment, sign in
-
-
Was working on a Spring Boot REST API the other day. Everything looked fine entity class, repository, controller all set up. But two fields, createdAt and updatedAt, were coming back null in every response. Spent time checking the constructor, the DTO mapping, the database config. Turns out I just needed two annotations: @CreationTimestamp → auto-sets the time when record is created @UpdateTimestamp → auto-updates the time on every save Two lines. That's it. Hibernate handles everything behind the scenes you don't set these manually. One more thing I'd missed without @JsonFormat, Java's Timestamp serializes weirdly in JSON. Add this and it formats cleanly: @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss") Small things. But they'll silently break your API if you miss them. #Java #SpringBoot #Backend #LearningInPublic #HibernateJPA
To view or add a comment, sign in
-
-
Spring Boot Annotations by Layers — A Complete Guide for Developers Understanding how Spring Boot annotations are structured across layers is essential for writing clean, scalable, and maintainable applications. Here’s a structured breakdown 👇 1. Controller Layer (Presentation Layer) Handles incoming HTTP requests & sends responses Annotations: ✔️ @RestController ✔️ @Controller ✔️ @RequestMapping ✔️ @GetMapping / @PostMapping / @PutMapping / @DeleteMapping ✔️ @RequestParam, @PathVariable, @RequestBody 2. Service Layer (Business Logic Layer) Contains core application logic Annotations: ✔️ @Service ✔️ @Component ✔️ @Transactional 3. Repository Layer (Persistence Layer) Interacts with the database Annotations: ✔️ @Repository ✔️ @EnableJpaRepositories ✔️ @Query ✔️ @Modifying 4. Entity Layer (Model Layer) Represents database tables Annotations: ✔️ @Entity ✔️ @Table ✔️ @Id ✔️ @GeneratedValue ✔️ @Column ✔️ @OneToMany / @ManyToOne / @ManyToMany 5. Configuration Layer Manages application setup Annotations: ✔️ @Configuration ✔️ @Bean ✔️ @ComponentScan ✔️ @EnableAutoConfiguration ✔️ @SpringBootApplication 6. Cross-Cutting Concerns (Common Across Layers) Annotations: ✔️ @Autowired, @Qualifier, @Primary ✔️ @Valid, @NotNull, @Size ✔️ @ControllerAdvice, @ExceptionHandler Why this matters? A clear understanding of these layers helps you: Write clean and modular code Improve scalability and maintainability Perform better in interviews Design real-world enterprise applications Always explain Spring Boot in this flow: Controller → Service → Repository → Entity → Configuration If you found this helpful, feel free to 👍 like, 💬 comment, and 🔖 save for future reference. #SpringBoot #Java #BackendDevelopment #Microservices #Programming #SoftwareEngineering #InterviewPreparation
To view or add a comment, sign in
-
More from this author
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
Exactly, Neeraj! Such small mistakes in choosing the right approach often leads to DB crash down and server failures!!