𝗔 𝗹𝗼𝘁 𝗼𝗳 𝗦𝗽𝗿𝗶𝗻𝗴 𝗱𝗲𝘃𝗲𝗹𝗼𝗽𝗲𝗿𝘀 𝘀𝘁𝗶𝗹𝗹 𝘁𝗵𝗶𝗻𝗸 𝘄𝗿𝗶𝘁𝗶𝗻𝗴 𝗾𝘂𝗲𝗿𝗶𝗲𝘀 𝗺𝗲𝗮𝗻𝘀 𝗼𝗻𝗹𝘆: • JPA method names • @Query But if your queries are getting more complex, 𝗷𝗢𝗢𝗤 𝗶𝘀 𝗮𝗹𝘀𝗼 𝗮𝗻 𝗼𝗽𝘁𝗶𝗼𝗻 — and honestly, more developers should know about it. In Spring, you can implement database queries in multiple ways: 𝗷𝗢𝗢𝗤 Great when your application is 𝗦𝗤𝗟-𝗵𝗲𝗮𝘃𝘆. 𝙒𝙝𝙮 𝙥𝙚𝙤𝙥𝙡𝙚 𝙡𝙞𝙠𝙚 𝙞𝙩: • type-safe SQL • better for complex joins • cleaner for reporting / analytics queries • stays close to real SQL 𝘽𝙚𝙨𝙩 𝙛𝙤𝙧: • advanced filtering • multi-table joins • database-driven applications 𝗝𝗗𝗕𝗖 The most direct way to talk to the database. 𝙒𝙝𝙮 𝙥𝙚𝙤𝙥𝙡𝙚 𝙪𝙨𝙚 𝙞𝙩: • full control • lightweight • no ORM magic 𝙏𝙧𝙖𝙙𝙚𝙤𝙛𝙛: • more boilerplate • manual mapping • less convenient as the project grows @𝗤𝘂𝗲𝗿𝘆 A very common middle ground in Spring. 𝙂𝙤𝙤𝙙 𝙛𝙤𝙧: • custom repository queries • when derived methods are not enough • medium-complexity use cases 𝙏𝙧𝙖𝙙𝙚𝙤𝙛𝙛: • query strings can get harder to maintain • not ideal when SQL becomes a big part of the app 𝗝𝗣𝗔 𝗱𝗲𝗿𝗶𝘃𝗲𝗱 𝗺𝗲𝘁𝗵𝗼𝗱𝘀 The fastest option for simple queries. 𝙂𝙤𝙤𝙙 𝙛𝙤𝙧: • CRUD • small filters • rapid development 𝙏𝙧𝙖𝙙𝙚𝙤𝙛𝙛: • method names can become ugly very fast • not made for complex query logic 𝗧𝗵𝗲 𝗿𝗲𝗮𝗹 𝗽𝗼𝗶𝗻𝘁: 𝗦𝗽𝗿𝗶𝗻𝗴 𝗱𝗼𝗲𝘀 𝗻𝗼𝘁 𝗳𝗼𝗿𝗰𝗲 𝘆𝗼𝘂 𝘁𝗼 𝘄𝗿𝗶𝘁𝗲 𝗲𝘃𝗲𝗿𝘆 𝗾𝘂𝗲𝗿𝘆 𝘁𝗵𝗲 𝘀𝗮𝗺𝗲 𝘄𝗮𝘆. 𝘈𝘯𝘥 𝘵𝘩𝘢𝘵’𝘴 𝘴𝘰𝘮𝘦𝘵𝘩𝘪𝘯𝘨 𝘢 𝘭𝘰𝘵 𝘰𝘧 𝘥𝘦𝘷𝘦𝘭𝘰𝘱𝘦𝘳𝘴 𝘰𝘷𝘦𝘳𝘭𝘰𝘰𝘬. • simple query → derived method • custom query → @Query • raw control → JDBC • serious SQL work → jOOQ Knowing Spring is not just knowing JPA. It’s knowing 𝘄𝗵𝗶𝗰𝗵 𝗱𝗮𝘁𝗮 𝗮𝗰𝗰𝗲𝘀𝘀 𝗮𝗽𝗽𝗿𝗼𝗮𝗰𝗵 𝗳𝗶𝘁𝘀 𝘁𝗵𝗲 𝗽𝗿𝗼𝗯𝗹𝗲𝗺 𝗯𝗲𝘀𝘁. 𝗛𝗮𝘃𝗲 𝘆𝗼𝘂 𝗲𝘃𝗲𝗿 𝘂𝘀𝗲𝗱 𝗷𝗢𝗢𝗤 𝗶𝗻 𝗮 𝗦𝗽𝗿𝗶𝗻𝗴 𝗽𝗿𝗼𝗷𝗲𝗰𝘁? #Java #SpringBoot #SpringFramework #JOOQ #JPA #JDBC #SQL #BackendDevelopment #SoftwareEngineering #Programming #Database #Tech
Choosing the Right Query Method in Spring: JPA, @Query, jOOQ, and JDBC
More Relevant Posts
-
When I first started with Spring Data JPA, this honestly felt like magic User findByEmail(String email); No SQL . No implementation. No query. And somehow… it worked. I used it for a long time before asking How is this actually possible? When I started with Spring Boot, I assumed this was just framework magic and I think many of us have felt the same. But that skips the most interesting part. It is not magic. It is a parser. Spring treats this method name: findByEmail() as a mini query language. Yes — the method name itself. Internally, Spring Data uses a parser called PartTree to read it. It breaks it into meaning like - * find → create a select query * By → start parsing criteria * Email → match an entity property If your entity has - private String email; Spring can derive a query from the method name.That is called query derivation using naming conventions.And this is where it gets deeper.Spring does not directly generate SQL.It first derives JPQL.Then Hibernate converts JPQL into database-specific SQL. This getSomeUserStuff() does not work. Because the parser does not understand it. But this findByEmailAndStatus() works because it follows a grammar.That is not just convention. That is a contract. And one detail many of use miss - Spring validates these derived queries at startup. Not later. So if you write: findByEmailAddress() but your entity does not have - emailAddress , your application can fail fast during startup. That is intentional framework design. Sometimes the most elegant engineering is hiding inside the APIs we use every day. #SpringBoot #Java #JPA #Hibernate #BackendDevelopment
To view or add a comment, sign in
-
𝗔𝗱𝘃𝗮𝗻𝗰𝗲𝗱 𝗤𝘂𝗲𝗿𝘆 𝗠𝗶𝗰𝗿𝗼𝘀𝗲𝗿𝘃𝗶𝗰𝗲 Mastering database queries with Spring Boot + JPA In real-world applications, the efficiency of your system often depends on how well you write database queries. While basic CRUD operations are simple, production systems require much more like efficient filtering, optimized joins, aggregations, and handling complex query scenarios. I built this microservice to demonstrate how modern backend systems handle basic to advanced querying patterns using Spring Boot and JPA. Source code: https://lnkd.in/g9b78BnS This project focuses on writing clean, efficient, and scalable queries which something every backend developer should master. 𝗛𝗶𝗴𝗵𝗹𝗶𝗴𝗵𝘁𝘀 • Real-world query scenarios exposed via REST APIs • Performance-focused design (N+1 problem and optimization) • Combination of JPA, JPQL, and native SQL • Practical handling of relational data • Clean and maintainable architecture 𝗪𝗵𝗮𝘁’𝘀 𝗖𝗼𝘃𝗲𝗿𝗲𝗱 • Derived queries (method name-based) • Pagination and sorting for large datasets • Search using LIKE queries • Join queries and fetch join optimization • N+1 problem and its solution • Aggregations (count, sum, group by) • Native SQL queries • Dynamic queries using Specification API • Projections (interface and DTO-based) • Subqueries (average, max, nested queries) • Exists / Not Exists queries • Window functions (ranking, top-N queries, running totals) • Indexed queries for performance • Relationship handling (one-to-many, many-to-many) • Soft delete implementation • Stored procedure integration 𝗪𝗵𝘆 𝗧𝗵𝗶𝘀 𝗠𝗮𝘁𝘁𝗲𝗿𝘀 Poorly written queries quickly become a bottleneck: • Slow APIs • High database load • Increased latency • Scalability limitations This project demonstrates how to avoid these issues using proper query design and optimization techniques. 𝗧𝗲𝗰𝗵 𝗦𝘁𝗮𝗰𝗸 • Java 21 • Spring Boot (REST APIs) • Spring Data JPA (Hibernate) • PostgreSQL • Lombok • Maven This project is useful for developers who want to: • Improve their JPA and SQL skills • Understand real-world query patterns • Learn performance optimization techniques "Efficient queries are the foundation of high-performance systems." #Java #SpringBoot #JPA #Hibernate #SQL #Database #BackendDevelopment #Microservices #Performance #SystemDesign #SoftwareEngineering
To view or add a comment, sign in
-
-
🚀 Mastering Persistence in Spring Data JPA: persist() vs. merge() vs. save() Ever wondered which method to use when saving data in Java? Choosing the wrong one can lead to unnecessary SQL queries or even dreaded EntityExistsException errors. Here is the breakdown of the "Big Three": 🔹 1. persist() – The "New Only" Approach What it does: Takes a brand-new (transient) entity and makes it managed. It schedules an INSERT. Best for: Creating new records when you are sure they don't exist yet. Watch out: It will throw an exception if the entity is already detached or has an ID that exists in the DB. 🔹 2. merge() – The "Reconnector" What it does: Takes a detached entity (one that was loaded in a different session) and copies its state onto a new managed version. Best for: Updating existing records that were passed through different layers of your app (e.g., from a REST controller). Watch out: It creates a copy. You must use the returned object for further changes! 🔹 3. save() – The Spring Data Way What it does: A smart wrapper provided by Spring Data JPA. It checks if the entity is "new." If yes, it calls persist(); if not, it calls merge(). Best for: Most standard repository patterns. It’s the "safe bet" for 90% of use cases. Watch out: Because it checks state first, it might trigger an extra SELECT query to decide whether to insert or update. 💡 Pro Tip: If you are building high-performance systems with massive inserts, using persist() directly via the EntityManager can sometimes be more efficient than the generic save() method. Check out the infographic below for a quick visual cheat sheet! 📊 #Java #SpringBoot #JPA #Hibernate #SoftwareEngineering #BackendDevelopment
To view or add a comment, sign in
-
-
Ever felt like SQL is doing more work than your actual logic? Writing queries… mapping results… handling connections… It gets repetitive really fast. What if you could just work with objects instead? That’s where 𝗢𝗥𝗠 (𝗢𝗯𝗷𝗲𝗰𝘁 𝗥𝗲𝗹𝗮𝘁𝗶𝗼𝗻𝗮𝗹 𝗠𝗮𝗽𝗽𝗶𝗻𝗴) comes in. Instead of writing complex SQL queries, you interact with your database using Java objects. No more manually converting 𝗿𝗼𝘄𝘀 → 𝗼𝗯𝗷𝗲𝗰𝘁𝘀. ORM does it for you. Let’s simplify it Without ORM: • Write SQL queries • Execute them • Map ResultSet to objects manually With ORM: • Create a class • Map it to a table • Call methods like save(), findById() That’s it. Popular ORM frameworks we might know: 𝗛𝗶𝗯𝗲𝗿𝗻𝗮𝘁𝗲 (most widely used) 𝗝𝗣𝗔 (Java Persistence API – standard) Why developers love ORM: • Faster development (less boilerplate) • Focus on business logic, not SQL • Automatic mapping between objects & tables • Easy integration with Spring Boot But here’s the real insight ORM is powerful… but blindly using it can hurt performance. Sometimes, writing a custom query is still the better choice. So the goal isn’t to avoid SQL… It’s to use 𝗢𝗥𝗠 𝘀𝗺𝗮𝗿𝘁𝗹𝘆. Next time you call 𝘀𝗮𝘃𝗲() in your project, remember — there’s a lot happening behind the scenes. #CoreJava #JavaDeveloper #Spring #Framework #ORM #SpringBoot #SpringData #Hibernate #SoftwareDevelopment #SQL #BackEndDevelopment #MicroServices #Programming #aswintech #Database #BuildBetter
To view or add a comment, sign in
-
Spring Boot DAY 26 – JPQL vs Native Query When working with Spring Data JPA, you often need custom queries. That’s where JPQL and Native Queries come into play 👇 🔹 JPQL (Java Persistence Query Language) JPQL is an object-oriented query language defined by Java Persistence API (JPA). It works with: ✔ Entity class names ✔ Java field names ✔ Object relationships 👉 It does NOT use table names or column names directly. ✅ Example: @Query("SELECT e FROM Employee e WHERE e.salary > :salary") List<Employee> findHighSalaryEmployees(@Param("salary") double salary); Here: Employee= Entity class salary= Java field 💡 JPQL works on the entity model, not the database schema. 🎯 Advantages: ✔ Database independent ✔ Cleaner & object-oriented ✔ Easy to maintain ✔ Portable across databases 🔹 Native Query Native Query uses pure SQL. It works with: ✔ Table names ✔ Column names ✔ Database-specific functions ✅ Example: @Query(value = "SELECT * FROM employee WHERE salary > :salary", nativeQuery = true) List<Employee> findHighSalaryEmployees(@Param("salary") double salary); Here: employee = Table name salary = Column name 💡 You are directly interacting with the database. 🎯 Advantages: ✔ Full database control ✔ Use complex joins ✔ Use DB-specific features (e.g., LIMIT, stored procedures) ✔ Better for performance tuning in complex cases 🆚 JPQL vs Native Query – Key Differences FeatureJPQLNative QueryQuery TypeObject-basedSQL-basedUsesEntity namesTable namesDB DependencyIndependentDB-specificPortabilityHighLowAdvanced SQLLimitedFull support🧠 When Should You Use What? ✅ Use JPQL when: You want database independence Your query is simple to moderate You prefer object-oriented coding ✅ Use Native Query when: You need complex joins You want database-specific optimization You are using stored procedures or advanced SQL 🎯 Simple Rule 👉 JPQL = Work with Objects 👉 Native Query = Work with Database Both are powerful. The smart developer chooses based on project requirements 💡 If you're learning Spring Boot, understanding this difference is crucial for writing optimized and maintainable applications 🚀
To view or add a comment, sign in
-
-
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
-
-
🚀 Backend Learning | Understanding the N+1 Query Problem While working on backend systems, I recently explored a common performance issue in ORM frameworks — the N+1 Query Problem. 🔹 The Problem: • Fetching related data triggers multiple queries instead of one • Example: 1 query for parent + N queries for child records • Leads to performance degradation and increased DB load 🔹 What I Learned: • Happens frequently in Hibernate / JPA due to lazy loading • Causes unnecessary database calls • Impacts scalability under large datasets 🔹 How to Fix: • Use JOIN FETCH to fetch related data in a single query • Apply Entity Graphs where needed • Optimize queries based on use-case 🔹 Outcome: • Reduced number of database queries • Improved application performance • Better handling of large datasets Sometimes performance issues are not about logic — they are about how data is fetched. 🚀 #Java #SpringBoot #Hibernate #JPA #BackendDevelopment #SystemDesign #Performance #LearningInPublic
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
-
⚠️ 𝕋𝕙𝕖 ℕ+𝟙 ℙ𝕣𝕠𝕓𝕝𝕖𝕞 — 𝕋𝕙𝕖 𝕊𝕚𝕝𝕖𝕟𝕥 𝕂𝕚𝕝𝕝𝕖𝕣 𝕠𝕗 𝕐𝕠𝕦𝕣 𝔹𝕒𝕔𝕜𝕖𝕟𝕕 ℙ𝕖𝕣𝕗𝕠𝕣𝕞𝕒𝕟𝕔𝕖 Everything looks fine in your code… Until your database starts suffering. You write something simple: 𝐋𝐢𝐬𝐭<𝐎𝐫𝐝𝐞𝐫> 𝐨𝐫𝐝𝐞𝐫𝐬 = 𝐨𝐫𝐝𝐞𝐫𝐑𝐞𝐩𝐨𝐬𝐢𝐭𝐨𝐫𝐲.𝐟𝐢𝐧𝐝𝐀𝐥𝐥(); Seems harmless, right? But under the hood, Hibernate might be doing this: 1 query → fetch all orders N queries → fetch each related entity (customers, products, etc.) 💥 𝗥𝗲𝘀𝘂𝗹𝘁: * Dozens (or hundreds) of unnecessary queries. * Increased latency. * Heavy database load. Performance degradation under traffic And the worst part? You often don’t notice it… until it’s too late. 🧠 𝗪𝗵𝘆 𝘁𝗵𝗶𝘀 𝗵𝗮𝗽𝗽𝗲𝗻𝘀 ? Because of lazy loading. Hibernate tries to be smart and loads relationships only when needed. But in loops or collections… it turns into a query explosion. 🛠️ 𝗛𝗼𝘄 𝘁𝗼 𝗳𝗶𝘅 𝗶𝘁 (𝗽𝗿𝗼𝗽𝗲𝗿𝗹𝘆): ✔️ 𝐉𝐎𝐈𝐍 𝐅𝐄𝐓𝐂𝐇 : Load related data in a single optimized query. ✔️ @𝐄𝐧𝐭𝐢𝐭𝐲𝐆𝐫𝐚𝐩𝐡 : Control fetching strategy declaratively. ✔️ 𝗗𝗧𝗢 𝗣𝗿𝗼𝗷𝗲𝗰𝘁𝗶𝗼𝗻𝘀 : Fetch only what you actually need (best for performance-critical paths). 💡 𝗥𝗲𝗮𝗹 𝘁𝗮𝗸𝗲𝗮𝘄𝗮𝘆 Performance issues are rarely in your business logic. They’re often in: 👉 How you fetch your data. 👉 How many queries you execute. 👉 How your ORM behaves behind the scenes. Good backend engineers don’t just write code that works, they write code that scales under pressure. #SpringBoot #Java #BackendDevelopment #Hibernate #PerformanceOptimization #SystemDesign #CleanCode
To view or add a comment, sign in
-
-
The N+1 Query Problem — A Silent Performance Killer In one of my recent backend discussions, we revisited a classic issue that often goes unnoticed during development but can severely impact performance in production — the N+1 Query Problem. What is the N+1 Problem? It occurs when your application executes: 1 query to fetch a list of records (N items) Then executes N additional queries to fetch related data for each record Total = 1 + N queries Example Scenario: You fetch a list of 100 users, and for each user, you fetch their orders separately. That results in 101 database queries instead of just 1 or 2 optimized queries. Why is it Dangerous? 1. Increased database load 2. Slower response time 3. Poor scalability under high traffic 4. Hard to detect in small datasets, but disastrous at scale How to Overcome It? 1. Use Join Fetch (Eager Loading) Fetch related entities in a single query using JOINs. 2. Batch Fetching Load related data in chunks instead of one-by-one queries. 3. Entity Graphs (JPA) Define what relationships should be fetched together dynamically. 4. Use DTO Projections Fetch only required fields instead of entire objects. 5. Caching Strategy Leverage second-level cache to reduce repeated DB hits. 6. Monitor SQL Logs Always keep an eye on generated queries during development. Pro Tip: The N+1 problem is not a bug — it’s a design inefficiency. It often comes from default lazy loading behavior in ORMs like Hibernate. Interview Insight: A good engineer doesn’t just make code work — they make it scale efficiently. #Java #SpringBoot #Hibernate #BackendDevelopment #PerformanceOptimization #Microservices #InterviewPrep
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