Your DTO might be triggering database queries This looks like a clean DTO. But it can silently hit your database. public record User(String name, List<Order> orders) {} 🧠 Somewhere in your code user.orders().size(); 🚨 What actually happens 👉 Depending on your JPA setup: triggers a lazy query or loads the full collection or causes N+1 issues 👉 all from a simple .size() 💥 Real impact hidden database calls unpredictable performance harder to debug in production ✅ Better approach public record UserDto(String name, int orderCount) {} 👉 and compute it at the query level: SELECT u.name, COUNT(o) FROM User u LEFT JOIN u.orders o GROUP BY u.name 🧠 Takeaway A DTO should not control when your database is queried. 🔍 Bonus I built a tool that detects issues like: N+1 queries lazy loading traps inefficient data access 👉 https://joptimize.io How many hidden queries are behind your DTOs? #JavaDev #SpringBoot #Hibernate #JavaPerformance #Backend
JOptimize’s Post
More Relevant Posts
-
Hidden N+1 in Spring Boot endpoint This endpoint runs 78 SQL queries… for a single request. And no one noticed. During a performance review, I analyzed a simple API: @GetMapping("/owners") public List<OwnerDto> getOwners() { return ownerRepository.findAll().stream() .map(owner -> new OwnerDto( owner.getId(), owner.getLastName(), owner.getPets().size() // ⚠️ hidden query )) .toList(); } Looks clean. Looks harmless. 🚨 What actually happens 1 query → fetch owners +1 query per owner → fetch pets 👉 With 77 owners: 1 + 77 = 78 SQL queries 💥 Real impact (measured) up to 1.2s per request ~29s cumulative DB time massive DB load under traffic ⚠️ Why this is hard to spot code looks clean no errors works fine in dev explodes only with real data ✅ Fix @EntityGraph(attributePaths = "pets") List<Owner> findAll(); 👉 Single query instead of dozens. 🧠 Takeaway Most performance issues are not in your code. They are in your data access patterns. 🔍 Bonus I built a small tool that detects this automatically: 👉 https://www.joptimize.io/ It highlights: N+1 queries slow endpoints hidden database overhead Are you sure your endpoints are not doing 10x more queries than expected? #JavaDev #SpringBoot #Hibernate #JavaPerformance #Backend #SoftwareEngineering
To view or add a comment, sign in
-
If you're using Java records with Spring Data JDBC, you've probably written this: new Meetup(null, title, date) That null shows up everywhere you create a new entity. Callers shouldn't have to know how the id gets populated. A static factory method fixes it. The canonical constructor still exists, so Spring Data JDBC can materialize rows from the database. Your application code just stops dealing with null. It's the same pattern you already use in the JDK: List.of, Map.of, LocalDate.of. Thinking about turning this into a video. Would it be useful?
To view or add a comment, sign in
-
-
Learn how to read Excel files in Java using Apache POI with simple examples, and step-by-step guidance for data-driven test automation. This article teaches the following: - What is Apache POI? - Apache POI Architecture - A step-by-step guide to read an Excel File with Apache POI with code example Read the full article here https://lnkd.in/dyzc2JZ6 #Excel #Java #TestAutomation #Tutorial #Testing #ApachePOI
To view or add a comment, sign in
-
Stop Hiding your Bugs ! try { //some logic that throws an exception } catch(Exception e ) { throw new RuntimeException(); } 1- loss of stack trace : throwing a new exception without passing the original one 2- Generic Obscurity : RuntimeException tells the caller nothing , it was a database issue ? a null pointer ? validation error ? 3- silent failure : impossible for high level handlers to catch specific issues and recover gracefully why this matters ? ==> we are resetting the history of an error. in java the constructor for exception allows you to pass the cause as parameter Exception (exception e ) tools like Sentry or ELK can show you the real caused by chain
To view or add a comment, sign in
-
Spring Boot Logging – What really happens when INFO is disabled? In production, we usually turn off INFO logs. It feels like those log statements are completely ignored — but that’s not always true. The key thing to understand is this: Java evaluates the log statement before the logging framework decides to ignore it. Take this example: log.info("User data: " + user); Here, the string concatenation happens first. That means user.toString() is executed and a new String object is created. Only after that, the logging framework checks the log level and ignores it. So even though nothing is printed, you still created objects, used memory, and added work for the Garbage Collector. Over time, this leads to more GC activity and unnecessary CPU usage. Now compare it with: log.info("User data: {}", user); This looks similar, but behaves very differently. In this case, the logging framework checks whether INFO is enabled before formatting the message. If INFO is disabled, it simply skips everything — no string creation, no extra objects, no GC work, and minimal CPU usage. There’s one more subtle case: log.info("User data: {}", getUser()); Even though you’re using {}, the method getUser() is still executed before the log call. So the object gets created anyway, consuming CPU and again adding pressure on the Garbage Collector — even when the log is disabled. To truly avoid unnecessary work, especially for expensive operations, you need to guard it: if (log.isInfoEnabled()) { log.info("User data: {}", getUser()); } Now, the method runs only when INFO logging is actually enabled, avoiding wasted computation, object creation, GC cycles, and CPU overhead. The takeaway is simple: Logging frameworks can skip formatting, but they cannot stop Java from executing expressions. Writing log statements the right way can save memory, reduce GC pressure, and improve CPU efficiency — especially in high-scale applications. #Java #SpringBoot #Logging #Performance #GarbageCollection #CleanCode
To view or add a comment, sign in
-
-
Building a C++ log storage engine — because the JVM has limits you can't always engineer around. Phase 5 of my distributed messaging system (Java) eliminated 655ms GC pauses and cut write p99.99 by 77% — but it also showed me where the JVM stops you: TLAB filler allocations you don't control, futex syscalls on every lock, object headers you can't remove. Phase 6 is a C++ port of the log storage engine, targeting the same SPSC benchmark. The constraints are different: - mmap + MAP_POPULATE + MAP_HUGETLB — pages pre-faulted at startup, 262,144 TLB entries → 512 - atomic<int64_t> with acquire/release replacing ReentrantReadWriteLock — zero syscalls on the read path - alignas(64) + C++ concepts enforcing cache line fit at compile time — no silent layout bugs - push() returns bool — the engine never blocks, never throws, backpressure is the caller's problem The benchmark measures the mmap store path only — msync excluded, flush policy is caller-determined. Same methodology as the Java numbers: bare-metal Linux, no artificial constraints. ADR written and reviewed before a single line of code. Code next. Java implementation: https://lnkd.in/gfANhFti Stay tuned: https://lnkd.in/gifTNMSB #cpp #lowlatency #hft #systemsprogramming #distributedsystems
To view or add a comment, sign in
-
Ever wondered what really happens when a JSON request hits a Spring Boot application? Here’s a quick, simplified journey ➡️ 1. Incoming Request (JSON) A client sends a JSON payload over HTTP. This request lands on the embedded server (usually Tomcat). ➡️ 2. Tomcat Thread Handling Tomcat assigns a thread from its pool to handle the request — this ensures multiple users can be served concurrently. ➡️ 3. Filters (Pre-processing) Before reaching your application logic, the request passes through filters (e.g., logging, CORS, security checks). ➡️ 4. DispatcherServlet (The Traffic Controller) Spring’s DispatcherServlet takes over — it’s the central hub that routes requests to the right components. ➡️ 5. Authentication & Security If security is enabled, Spring Security intercepts the request, validates tokens/credentials, and decides access. ➡️ 6. Handler Mapping DispatcherServlet finds the correct controller method based on URL, HTTP method, and annotations. ➡️ 7. JSON → Java Object (Jackson Magic) The request body is converted into a Java object using Jackson (via HttpMessageConverters). ➡️ 8. Controller Execution Your controller method runs with the mapped object and business logic kicks in. ➡️ 9. Response Flow Back The response object is converted back to JSON and sent through the same chain (in reverse). 💡 In short: JSON → Tomcat Thread → Filters → DispatcherServlet → Security → Controller Mapping → Object Conversion → Business Logic → Response Clean, structured, and highly extensible — that’s the beauty of Spring Boot. #SpringBoot #Java #BackendDevelopment #SoftwareEngineering #WebDevelopment #KSAJobs #RiyadhJobs #OpenToWork
To view or add a comment, sign in
-
Fetching a multi-level hierarchy from a relational database is a classic performance bottleneck. If you do it wrong, you end up with the dreaded N+1 query problem or a Cartesian product that brings your application to its knees. In this session, Java Champion Vlad Mihalcea delves into the most efficient strategies for retrieving complex data structures—specifically for scenarios where you need to store the result set in a cache like Redis. Join us: luma.com/6wrxlqj3
To view or add a comment, sign in
-
💡 𝐒𝐩𝐫𝐢𝐧𝐠 𝐃𝐚𝐭𝐚 𝐄𝐧𝐯𝐞𝐫𝐬 - 𝐚𝐮𝐝𝐢𝐭𝐢𝐧𝐠 𝐰𝐢𝐭𝐡𝐨𝐮𝐭 𝐭𝐡𝐞 𝐨𝐯𝐞𝐫𝐡𝐞𝐚𝐝 👉 Spring Data Envers adds automatic change tracking for your entities. ⚙️ Built on top of Hibernate Envers and seamlessly integrates with Spring Data JPA. ⁉️ What it gives you: ✔️ Full history of entity changes ✔️ Who changed what and when ✔️ Access to any previous state ✔️ Built-in versioning (revisions) ⚡ Minimal setup: @Entity @Audited public class User { @Id private Long id; private String name; } ➡️ Every change = new revision stored automatically 🚀 Use it when: ▪️ Audit logs (finance, security) ▪️ Versioning / history tracking ▪️ Rollbacks to previous states ▪️ User activity tracking 📌 Clean, reliable way to add auditing without reinventing the wheel. #SpringBoot #Java #BackendDevelopment #SoftwareEngineering #ProgrammingTips
To view or add a comment, sign in
-
-
I recently built nerv-audit, a library on top of Hibernate Envers focused on vertical auditing. Most audit discussions focus on system-wide (horizontal) logs. But in practice, debugging usually comes down to a simpler question: 👉 What exactly changed in this entity? That’s where vertical auditing shines: • Clear, per-entity history • Precise diffs you can actually reason about • Less noise compared to aggregated audit streams • Better alignment with domain-driven design Instead of reconstructing state from a global timeline, you can directly inspect the evolution of a single entity with confidence. GitHub: https://lnkd.in/gSBi_ksN Curious how others approach auditing in their systems — vertical, horizontal, or a mix? #java #springboot #hibernate #ddd #softwareengineering
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