🚀Still confused about how collections are stored in the database using JPA? Most developers use List, Set, or Map in their entities… But very few actually understand how Spring Data JPA maps them behind the scenes. This visual breaks it down in a clean, professional way 👇 🔍 What this image explains 🧩 Entity to Database Mapping How a simple @Entity maps to database tables How @ElementCollection creates a separate table automatically How embedded objects (@Embeddable) structure your data 👉 Example: A Student with multiple Courses becomes: STUDENT table STUDENT_COURSES table (for collection mapping) 📦 Types of Collections in JPA 🔹 List<E> ✔ Ordered collection ✔ Allows duplicates ✔ Stored with index (if needed) 🔹 Set<E> ✔ No duplicates ✔ Unordered ✔ Better for uniqueness 🔹 Map<K, V> ✔ Key-value structure ✔ Useful for dynamic associations 🔹 EnumSet<E> ✔ Efficient storage for enum values ✔ Stored as ordinal or string ⚙️ What Happens Internally? 👉 JPA doesn’t store collections in a single column. Instead, it creates a separate lookup table and manages relationships automatically. This is where many beginners get confused — but once you understand this, your database design improves instantly. 💡 Why This Matters ✅ Clean database structure ✅ Better performance & normalization ✅ Scalable entity relationships ✅ Crucial for real-world backend systems 🔥 Pro Insight: Using collections is easy… Designing them correctly in JPA is what makes you a real backend developer. 💬 Question: Which collection do you use most in your projects — List or Set? #SpringBoot #Java #JPA #Hibernate #BackendDevelopment #SoftwareEngineering #DatabaseDesign #JavaDeveloper #LearningInPublic #TechContent
Anis Rahman’s Post
More Relevant Posts
-
🚀Still confused about how collections are stored in the database using JPA? Most developers use List, Set, or Map in their entities… But very few actually understand how Spring Data JPA maps them behind the scenes. This visual breaks it down in a clean, professional way 👇 🔍 What this image explains 🧩 Entity to Database Mapping How a simple @Entity maps to database tables How @ElementCollection creates a separate table automatically How embedded objects (@Embeddable) structure your data 👉 Example: A Student with multiple Courses becomes: STUDENT table STUDENT_COURSES table (for collection mapping) 📦 Types of Collections in JPA 🔹 List<E> ✔ Ordered collection ✔ Allows duplicates ✔ Stored with index (if needed) 🔹 Set<E> ✔ No duplicates ✔ Unordered ✔ Better for uniqueness 🔹 Map<K, V> ✔ Key-value structure ✔ Useful for dynamic associations 🔹 EnumSet<E> ✔ Efficient storage for enum values ✔ Stored as ordinal or string ⚙️ What Happens Internally? 👉 JPA doesn’t store collections in a single column. Instead, it creates a separate lookup table and manages relationships automatically. This is where many beginners get confused — but once you understand this, your database design improves instantly. 💡 Why This Matters ✅ Clean database structure ✅ Better performance & normalization ✅ Scalable entity relationships ✅ Crucial for real-world backend systems 🔥 Pro Insight: Using collections is easy… Designing them correctly in JPA is what makes you a real backend developer. 💬 Question: Which collection do you use most in your projects — List or Set? #SpringBoot #Java #JPA #Hibernate #BackendDevelopment #SoftwareEngineering #DatabaseDesign #JavaDeveloper #LearningInPublic #TechContent
To view or add a comment, sign in
-
-
🚀 Still confused about One-to-Many mapping in JPA? Let’s simplify it. If you’ve ever struggled with managing relationships like 👉 “One department → many employees” then this concept is a must-know for every backend developer. 🔍 What this image explains 👉 One-to-Many Association means: One parent entity is connected to multiple child entities. 💡 Real-world example: 🏢 One Department can have many Employees 👨💻 But each Employee belongs to only one Department 🧩 How it works in Spring Data JPA ✔ @OneToMany → Defines relationship on parent side ✔ @ManyToOne → Defines relationship on child side ✔ mappedBy → Avoids extra join table ✔ @JoinColumn → Creates foreign key in child table ✔ cascade = ALL → Saves parent + children together ✔ fetch = LAZY → Loads data only when needed 🗄️ Database Structure Instead of duplicating data: 👉 JPA creates a clean relationship using a foreign key departments (Parent Table) employees (Child Table with department_id) 🔗 This ensures proper linkage without redundancy 💡 Why this matters ✔ Represents real-world relationships clearly ✔ Reduces complex SQL joins ✔ Keeps database normalized ✔ Improves maintainability 🔥 Pro Insight: Always define mappedBy on the parent side — otherwise, JPA creates an unnecessary extra join table (common mistake ❌) ⚡ Golden Rule: Design relationships carefully — because bad mapping = bad performance. 💬 Question: Do you prefer unidirectional or bidirectional mapping in your projects? #SpringBoot #Java #JPA #Hibernate #BackendDevelopment #SoftwareEngineering #DatabaseDesign #LearningInPublic #Developers #TechContent
To view or add a comment, sign in
-
-
🚀 Still confused when to use One-to-One mapping in JPA? Most developers know @OneToOne… But very few understand how it actually works behind the scenes and when to use it correctly. This visual breaks it down in a clean + practical way 👇 🔍 What this image explains 👉 One-to-One Association means: Each record in one table is linked to exactly one record in another table. 💡 Real-world example: A User has exactly one UserDetails (email, phone, etc.) 🧩 How it works in Spring Data JPA ✔ @OneToOne → Defines the relationship ✔ @JoinColumn → Creates foreign key ✔ @MapsId → Shares primary key between tables ✔ cascade = ALL → Saves both entities together ✔ fetch = LAZY → Loads data only when needed 🗄️ Database Design Instead of storing everything in one table: 👉 JPA splits data into related tables users → basic info user_details → additional info 🔗 Connected using Primary Key + Foreign Key 💡 Why this matters ✔ Better data organization ✔ Cleaner architecture ✔ Avoids redundant data ✔ Improves performance in large systems 🔥 Pro Insight: Use One-to-One only when the relationship is strong and mandatory. Otherwise, you might be over-engineering your design. ⚡ Golden Rule: Think in objects, not tables — JPA handles the relationship for you. 💬 Question: Have you used @MapsId in your projects or still using basic mapping? #SpringBoot #Java #JPA #Hibernate #BackendDevelopment #SoftwareEngineering #DatabaseDesign #LearningInPublic #Developers #TechContent
To view or add a comment, sign in
-
-
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
-
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
-
-
𝗔𝗱𝘃𝗮𝗻𝗰𝗲𝗱 𝗤𝘂𝗲𝗿𝘆 𝗠𝗶𝗰𝗿𝗼𝘀𝗲𝗿𝘃𝗶𝗰𝗲 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
-
-
🚀 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
-
-
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
-
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
-
🚀 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
-
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