🔥 Day 41 of My Spring Boot Journey Today I explored some powerful features of Spring Data JPA that can significantly optimize database operations 📌 What I learned: ✅ Static Projection → Fetch only required fields using interface-based projections ✅ Dynamic Projection → Create flexible queries where the result type can be decided at runtime ✅ Custom Queries (JPQL & Native SQL) → Write optimized queries using @Query → Use @Param for named parameters → Perform UPDATE & INSERT using @Modifying and @Transactional 💡 Key takeaway: Instead of fetching entire entities, projections help improve performance and make APIs more efficient. Also understood the difference between: 🔹 SQL → works on tables 🔹 JPQL → works on entity classes 📁 Implemented all concepts with hands-on projects including: ✔ Static Projection ✔ Dynamic Projection ✔ Custom Queries Big thanks to my mentor for simplifying these advanced concepts 🙌 #SpringBoot #Java #BackendDevelopment #JPA #Hibernate #LearningInPublic #100DaysOfCode Hyder Abbas
Optimizing Database Operations with Spring Data JPA
More Relevant Posts
-
I used to think using Spring Data JPA meant I didn’t really need to worry about SQL anymore. It felt too easy. 😅 I remember building a feature that looked perfectly fine in code, clean repositories, simple method names, everything “just worked.” Until I started testing it with more data and suddenly the API got slower… and slower. 🐢 Not crashing. Not failing. Just… slower. I opened the logs and saw a flood of queries. One for users, then one for each user’s orders. 📄📄📄 That’s when it hit me, I had no idea what queries were actually running behind my code. That moment was a bit uncomfortable everything “worked”, but I clearly didn’t understand what was happening. 😬 A few things became very real after that: JPA hides complexity, but it doesn’t remove it 🎭 JPA makes things easy, but it doesn’t make database behavior go away ⚠️ Just because you didn’t write the query doesn’t mean it’s efficient. You still need to understand what’s being generated 🔍 Lazy vs eager loading isn’t just theory, it directly impacts performance ⚙️ That innocent looking repository method? It can cause an N+1 problem real quick 🚨 In real systems, this doesn’t show up during basic testing. It shows up as slow endpoints, high DB usage and confusing debugging sessions. 🧩 Now, I still use JPA the same way but I don’t trust it blindly. I check queries, think about fetching strategies and pay attention to what’s happening underneath. 👨💻 What I learned: If you’re using JPA without understanding the queries, you are debugging in the dark. Have you ever been surprised by what JPA was doing behind the scenes? 🤔 #Java #SoftwareEngineer #SpringMVC #SpringBoot #SpringDataJPA
To view or add a comment, sign in
-
Day 23. I stopped writing raw SQL in my repositories. Not because SQL is bad. Because Spring Data JPA was already doing it for me. And I didn’t know. I used to write this: @Query("SELECT * FROM users WHERE email = :email", nativeQuery = true) User findByEmail(@Param("email") String email); It worked. Until I realized I was solving a problem the framework had already solved. Here’s what actually happens: → Queries tied directly to database structure → Harder to refactor when schema changes → Less readable for other developers → You bypass what Spring Data JPA already gives you That’s not flexibility. That’s unnecessary complexity. So I changed it. (see implementation below 👇) User findByEmail(String email); No SQL. Same result. Better readability. Now: → Let JPA generate simple queries → Use @Query only when needed → Native SQL only for edge cases The hard truth: → Writing SQL feels powerful → But overusing it makes your code rigid → Most queries don’t need it Using SQL is easy. Knowing when NOT to use it is what makes you a backend developer. Are you still writing SQL for simple queries? 👇 Drop it below #SpringBoot #Java #JPA #BackendDevelopment #JavaDeveloper
To view or add a comment, sign in
-
-
🚀 Spring Data JPA: Simplifying Database Access When building backend applications, handling databases can quickly become painful (SQL, mapping, boilerplate code...). 👉 That’s where Spring Data JPA makes a real difference. 🔹 What is it? Spring Data JPA is an abstraction that allows you to interact with your database using Java objects, based on the ORM (Object-Relational Mapping) concept. 🔹 How does it work? Define entities (@Entity) that map to database tables Create repositories (interfaces) Let Spring automatically generate SQL queries ➡️ Result: less code, more productivity. 🔹 Simple example: @Entity public class User { @Id @GeneratedValue private Long id; private String name; } public interface UserRepository extends JpaRepository<User, Long> { List<User> findByName(String name); } 🔥 With just one line, you can fetch data without writing any SQL. 💡 Why use it? ✔ Huge time saver ✔ Cleaner code ✔ Easier maintenance ✔ Perfect for modern applications 📌 In short: Spring Data JPA lets you focus on business logic instead of database plumbing. #Java #SpringBoot #JPA #Backend #SoftwareEngineering
To view or add a comment, sign in
-
-
A while back I posted about a self-referencing customer hierarchy and asked how you'd approach it in production. Today I want to get into the first solution. 🔗 Original post in the comments. 🛑 The naive approach is querying in a loop. Fetch a customer. Check the parent. Fetch the parent. Check its parent. Repeat until you hit the root. It works. But every step is a separate database round trip. On a deep hierarchy under real traffic, that adds up fast. 🟢 There's a better way — already built into your database. 🔁 Recursive CTE(Common Table Expression) — let the database do the looping You give the database two things: A starting point — the customer you care about A repeating rule — "find the parent of whatever row you just found" The database keeps applying that rule, accumulating rows, until it hits a node with no parent. Then it returns everything at once — one query, one round trip, any depth. No extra tables. No schema changes. The complexity lives in the query, not the data model. The cost? The chain is recomputed on every read. Deep trees under heavy traffic will feel it. Best for: hierarchies that change frequently, moderate read load. #SystemDesign #Databases #Java #JPA #Hibernate
To view or add a comment, sign in
-
-
"How do you handle slow database queries in Spring Boot?" This comes up in almost every backend interview Most developers jump straight to indexing But that is only part of the answer The real question is why is the query slow in the first place Common causes N+1 queries hitting the database repeatedly Fetching more data than needed Missing pagination on large datasets Wrong fetch type EAGER instead of LAZY Before adding indexes check these Use @Query with JOIN FETCH to avoid N+1 Select only the fields you need not the entire entity Add pagination with Pageable for large results Set fetch = FetchType LAZY and load relations only when needed Indexes help but fixing the query design helps more What database optimization has saved you the most time #Java #SpringBoot #Database #BackendDevelopment #Optimization
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
-
Optimizing for Milliseconds: Building a Custom Trie Search 🚀 As my logistics project, Vela Route, grows, I realized that standard database queries wasn't enough for the "search-as-you-type" experience I wanted. Today, I moved beyond CRUD and implemented a custom Trie (Prefix Tree) data structure in Java. 🧠 The Challenge: Database LIKE queries can get sluggish as records scale. 🛠️ The Solution: I built an in-memory Retrieval Tree that "warm-starts" via a Spring Boot CommandLineRunner. ⚡ The Result: Tracking number lookups now happen in $O(L)$ time (based only on the length of the string), making the search nearly instantaneous regardless of database size. It’s been an incredible deep dive into memory management, recursion, and bridging the gap between PostgreSQL and RAM. Check out the implementation on my GitHub! #Java #SpringBoot #DataStructures #SoftwareEngineering #VelaRoute #BackendDevelopment #Trie #CodingBootcamp #BuildingInPublic
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
-
-
The N+1 problem happens when your application fetches a list of entities with one query, but then triggers an additional query for each item when accessing related data—often due to lazy loading in ORMs like JPA. What looks like a simple loop in code can result in dozens or hundreds of database calls, increasing latency, stressing the connection pool, and degrading performance under load. It’s not a logic bug but a data access design issue, where the way data is fetched doesn’t match how it’s used, causing the system to quietly slow down as scale increases #Java #SpringBoot #JPA #Hibernate #SystemDesign #Performance #BackendEngineering #Microservices #SoftwareEngineering #Scalability 🔥 Your loop has 1 line → Your database executes 100 queries ⚠️ Works perfectly in dev → Breaks silently under real traffic 📉 Not a logic bug → A hidden data access design flaw 🚨 Lazy loading = invisible performance killer 🧠 N+1 is not a loop problem → It’s a query shape problem 🔥 One-Line Takeaway Your loop didn’t break performance. Your data access pattern did.
To view or add a comment, sign in
-
-
ORM vs Raw SQL — Which one should YOU use? Two ways to talk to a database. Both powerful. Both have trade-offs. ORM (Object Relational Mapping) → You write code using models & methods → The ORM layer auto-generates the SQL → Returns hydrated model objects ✅ Faster development, less code, database agnostic ⚠️ But adds overhead & less control on complex queries Raw SQL → You write the exact SQL query → App sends it directly to the database → Returns raw rows ✅ Full control, better performance, ideal for complex joins & aggregations ⚠️ But requires SQL knowledge & more verbose code 🔑 Key Tradeoff: | | ORM | Raw SQL | |---|---|---| | Dev Speed | ⚡ High | Lower | | Query Control | Limited | Full | | Best For | CRUD & Rapid Dev | Complex Queries | 💡 My take: Use ORM for 80% of your daily CRUD work. Switch to Raw SQL when performance matters or queries get complex. In Spring Boot? Spring Data JPA = ORM, JdbcTemplate / Native Queries = Raw SQL. Best devs know when to use which! 🚀 #Java #SpringBoot #SQL #ORM #JPA #BackendDevelopment #DatabaseDesign #SoftwareEngineering
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
Intellij IDEA Community is better and easier to use. just in case