I optimized a query that was taking 45 seconds down to 200ms. Here's exactly what I did: After 9 years with Java + Spring Boot + various databases, here are the database lessons that actually matter: 1. Indexes are not magic, they're a trade-off Every index speeds up reads but slows down writes Index what you query, not everything 2. N+1 queries will kill your app Use JOIN FETCH in JPQL or @EntityGraph Always check the SQL Hibernate is generating 3. Pagination is non-negotiable findAll() on a 10M row table is a career-limiting move Spring Data's Pageable is your best friend 4. Connection pools matter more than you think HikariCP defaults are a starting point, not gospel Monitor your pool metrics in production 5. Read replicas for read-heavy workloads Your reporting queries shouldn't compete with your transactional queries 6. EXPLAIN ANALYZE before any optimization Never guess. Always measure. Most performance problems I've seen weren't code problems. They were database design problems. What's your worst database horror story? #Java #SpringBoot #Database #Performance #SQL #BackendDevelopment
Optimizing Database Queries with Java and Spring Boot
More Relevant Posts
-
Your database is not the problem. Your queries are. A slow application doesn't always mean you need a bigger server or a fancier cache. Most of the time, the bottleneck is sitting right there in a query nobody questioned. Spring Boot, or ORMs in general makes data access so easy that it's tempting to just let JPA handle everything. And it will, until it won't. The classic traps: N+1 queries. You fetch a list of 100 orders. Then for each order, JPA quietly fires another query to get the customer. That's 101 queries instead of 1. Feels fine in dev with 10 rows. Falls apart in prod with 100,000. Fetching everything when you need one field. findById() returns the full entity when the screen only needs a name and a date. Multiply that by thousands of requests and you're moving data for no reason. No pagination. findAll() sounds harmless. Until your table hits 2 million rows and you just loaded all of them into memory. Ignoring indexes. A query that runs in 3ms on 1,000 rows runs in 4 seconds on 1,000,000 if the column isn't indexed. The code didn't change. The data did. Use @Query when the query matters. Use projections or DTOs to fetch only what you need. Add @EntityGraph to control fetching explicitly. Paginate by default. And always look at the actual SQL being generated. What Hibernate writes is not always what you'd write. Performance issues are rarely mysterious. They're usually a query doing too much, too often, or too blindly. Read your queries like they cost money. Because in production, they do ! #SpringBoot #Java #DatabasePerformance #BackendDevelopment #SoftwareEngineering #CleanCode #JPA #Hibernate #TechTips #WebDevelopment
To view or add a comment, sign in
-
-
🚀 Stop Confusing JPQL with SQL — This Might Be Holding You Back! Most beginners in Spring Boot make this mistake 👇 They treat JPQL and SQL as the same thing… but they’re NOT. Let’s simplify it 🔥 🔹 JPQL = Works on Java Objects (Entities) 🔹 SQL = Works on Database Tables 👉 That’s it. That’s the core difference. But here’s where it gets interesting 👇 ⚡ JPQL ✔ Cleaner & object-oriented ✔ Database independent ✔ Perfect for JPA/Hibernate projects ⚡ SQL (MySQL) ✔ More control over queries ✔ Better for complex joins ✔ Needed for performance tuning --- 💡 Real Developer Insight: If you're only using JPQL, you're missing control. If you're only using SQL, you're missing abstraction. 👉 Smart developers know WHEN to use WHAT. --- 🎯 Interview Gold Line: “JPQL works on entities, SQL works on tables.” --- If this cleared your confusion, drop a 👍 and follow for more real backend concepts! #Java #SpringBoot #JPA #Hibernate #BackendDevelopment #SQL #CodingTips #Developers #Learning
To view or add a comment, sign in
-
-
I wrote "Clean Code" that silently killed our database performance. 📉🐢 It worked perfectly on my local machine. The tests passed. The UI was fast. But as soon as we hit 50 concurrent users in staging, the database CPU spiked to 90%. The Mistake: I was fetching a list of Orders, and for each order, I was calling order.getUser().getName(). In my head, it was one simple query. In reality, Spring was executing: 👉 1 query to get all Orders. 👉 100 extra queries to get each User. This is the classic N+1 Problem, and in a microservices environment, it’s a death sentence for your latency. The 2026 Solution (My Fix): Instead of a basic.findAll(), I moved to a custom @Query with a JOIN FETCH. java @Query("SELECT o FROM Order o JOIN FETCH o.user") List<Order> findAllWithUsers(); Use the code with caution. The Result? One single, efficient query. Database CPU dropped back to 10%. API response time cut by 70%. Lesson Learned: Don't just trust the "magic" of JPA. Always check your logs to see what Hibernate is actually doing behind the scenes. Have you ever been surprised by a "hidden" query? What’s your go-to tool for monitoring SQL in Spring Boot? 👇 #SpringBoot #JavaDeveloper #BackendEngineering #PerformanceOptimization #LearningInPublic #AhmedabadTech #CleanCode #Database
To view or add a comment, sign in
-
Day 15. My query was slow. Not because of bad code. Because of a missing index. I had this: @Query("SELECT u FROM User u WHERE u.email = :email") User findByEmail(@Param("email") String email); Looks fine. It’s not. Here’s what was actually happening: → 1 million users in the database → Every search = full table scan → Response time: 3–4 seconds per request That’s not slow code. That’s a missing index. Your code looks fine. Your database is doing all the work. The fix is simple: Tell the database where to look. @Entity @Table(name = "users", indexes = { @Index(name = "idx_user_email", columnList = "email") }) public class User { private String email; } What actually changes: → Speed — full table scan becomes instant lookup → Scalability — fine at 1K rows, critical at 1M → Cost — fewer resources, faster queries The hard truth: → ORMs don’t add indexes for you → You won’t notice this in development → You WILL notice it in production Writing queries is easy. Knowing why they’re slow is what makes you a backend developer. Are you adding indexes to your tables? 👇 Drop it below #SpringBoot #Java #MySQL #BackendDevelopment #JavaDeveloper
To view or add a comment, sign in
-
I released Scythe — an open-source SQL compiler and linter built in Rust. Write SQL. Generate type-safe, idiomatic database access code. No ORM needed. The problem: ORMs add bloat, hide performance issues, and create hard-to-debug edge cases. SQL is already a mature, type-safe language — it should be the source of truth. What Scythe does: It parses your SQL schema and queries, infers types and nullability statically, and generates production-ready code for your language and database driver of choice. 10 languages, 25 driver backends: - Rust (sqlx, tokio-postgres) - Python (psycopg3, asyncpg, aiomysql, aiosqlite) - TypeScript (postgres.js, pg, mysql2, better-sqlite3) - Go (pgx, database/sql) - Java & Kotlin (JDBC) - C# (Npgsql, MySqlConnector, Microsoft.Data.Sqlite) - Elixir (Postgrex, MyXQL, Exqlite) - Ruby (pg, mysql2, sqlite3) - PHP (PDO) 3 databases: PostgreSQL, MySQL, SQLite Beyond codegen, Scythe ships with 93 SQL lint rules, SQL formatting, and a migration path from sqlc. If you've used sqlc in Go — this is that idea taken further, for every major backend language. GitHub: https://lnkd.in/ds5sRUEM Docs: https://lnkd.in/dCHW3PVB crates.io: https://lnkd.in/dVk3_r-y #OpenSource #Rust #SQL #Backend #Database #TypeSafe #CodeGeneration #PostgreSQL #MySQL #SQLite #Python #TypeScript #Golang #Java #Kotlin #CSharp #Elixir #Ruby #PHP #DeveloperTools #WebDevelopment #SoftwareEngineering
To view or add a comment, sign in
-
I thought our Spring Boot API was fast… until we hit 1,000 users Everything worked perfectly in my local environment. But in production, our dashboard became painfully slow. The logs told the real story: Hundreds of SQL queries… for a single request. I had accidentally introduced the infamous N+1 Query Problem. 🔴 The Mistake I was fetching Users and their Orders using "findAll()". Since the relationship was "FetchType.LAZY" (default), Hibernate did this: • 1 query → fetch all Users • N queries → fetch Orders for each User 👉 With 1,000 users = 1,001 database calls for one page load 😬 🟢 The Fix Used "JOIN FETCH" in a custom query: @Query("SELECT u FROM User u JOIN FETCH u.orders") List<User> findAllWithOrders(); This forces Hibernate to fetch everything in a single SQL join. ⚡ The Result • Database calls: 1,001 → 1 • Response time: 5s → <200ms • Server CPU: Stable again 📌 The Lesson Performance issues often hide in “innocent” code. Don’t blindly trust default JPA behavior. Always monitor SQL logs during development — your future self will thank you. Have you ever been bitten by the N+1 problem? What’s your go-to solution — "JOIN FETCH" or "EntityGraph"? #Java #SpringBoot #Hibernate #BackendDevelopment #Performance #DatabaseOptimization #CleanCode
To view or add a comment, sign in
-
𝗔 𝗹𝗼𝘁 𝗼𝗳 𝗦𝗽𝗿𝗶𝗻𝗴 𝗱𝗲𝘃𝗲𝗹𝗼𝗽𝗲𝗿𝘀 𝘀𝘁𝗶𝗹𝗹 𝘁𝗵𝗶𝗻𝗸 𝘄𝗿𝗶𝘁𝗶𝗻𝗴 𝗾𝘂𝗲𝗿𝗶𝗲𝘀 𝗺𝗲𝗮𝗻𝘀 𝗼𝗻𝗹𝘆: • 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
To view or add a comment, sign in
-
Most developers use Spring Data JPA… But very few actually understand what happens behind this: userRepository.findByName("Sharief"); No SQL. No JDBC. No boilerplate. But internally 👇 → Spring reads the method name → Creates a proxy implementation → Delegates to Hibernate → Hibernate generates SQL → Database executes it → Result comes back as Java objects 💡 The important truth Spring doesn’t remove SQL. 👉 It writes SQL for you ⚠️ And this matters more than you think If you don’t understand this: →You may write inefficient queries →You may face performance issues →You’ll struggle in debugging 🚀 Final thought Spring Data JPA is powerful… But it’s not magic. Once you understand what’s happening behind the scenes, you start using it with intent, not assumptions. #SpringBoot #Java #BackendDevelopment #JPA #Hibernate
To view or add a comment, sign in
-
-
🚀 Spring Boot + Database Views & Stored Procedures (Hands-on) Recently, I worked on a backend project where I implemented Database Views and Stored Procedures using Spring Data JPA. 💡 What I built: ✔ Fetched data using database Views (user_view, user_department_view) ✔ Used Stored Procedures (GetUsersBySalary, GetUsersByDepartment) ✔ Wrote native SQL queries with @Query ✔ Mapped results to DTOs for clean API responses ✔ Handled JOINs at database level instead of Java 🔥 Key Learning: Working closer to the database helps in building more optimized and scalable backend systems. 💬 This project helped me understand how real-world applications handle data efficiently using DB-level logic instead of overloading the backend. Open to feedback & suggestions 🚀 git repo: https://lnkd.in/dQ92fr3Z #SpringBoot #Java #JPA #Hibernate #MySQL #BackendDevelopment #SoftwareEngineering #StoredProcedure #DatabaseDesign #APIs #LearningByDoing
To view or add a comment, sign in
-
I read two JetBrains articles recently that seem to completely contradict each other. One says: ❌ don't use data classes for entities in Kotlin. The other says: ✅ data classes are a great fit for entities. Same company. Opposite advice. The difference? One is about JPA. The other is about Spring Data JDBC. Here's why it matters. ── Spring Data JPA (Hibernate) manages entities as tracked, mutable objects. To do that, it needs to: → create proxy subclasses for lazy loading (class must be non-final) → call a no-arg constructor when loading from DB → inject fields via reflection after construction (fields must be mutable) Kotlin's data class breaks all three of these. Final. Immutable. No no-arg constructor. ── Spring Data JDBC is a completely different philosophy. No dirty checking. No proxies. No lazy loading. You call save() → SQL runs. You call findById() → result maps to your object. That's it. And because it uses constructor-based mapping, data classes are a natural fit. Immutable val fields? Great. final class? No problem. copy() to update instead of mutation? That's exactly the pattern. ── So "don't use data classes for entities" really means "...when using JPA." It's not a rule about Kotlin + databases in general. The two frameworks look similar from the outside — both are Spring Data, both talk to relational DBs. But they have fundamentally different models for how objects and databases interact. Once you see that, the contradiction disappears. 📝 Wrote a full breakdown on Medium — link in the comments. #Kotlin #SpringBoot #SpringData #JPA #Backend
To view or add a comment, sign in
-
Explore related topics
- Tips for Database Performance Optimization
- How to Optimize Query Strategies
- How to Optimize SQL Server Performance
- How to Analyze Database Performance
- How to Improve NOSQL Database Performance
- How Indexing Improves Query Performance
- Tips for Optimizing App Performance Testing
- How to Optimize Postgresql Database Performance
- How to Optimize Cloud Database Performance
- How to Improve Code Performance
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