🔥 Mapping in Spring Boot (Manual vs MapStruct) Mapping = converting one object to another (DTO ↔ Entity) 🤔 Why use mapping? 1. Clean separation of layers (Controller ↔ Service ↔ DB) 2. Avoid exposing internal entities 3. Better control over data transformation ⚔️ Manual vs MapStruct 🧱 Manual Mapping ✔ Full control ✔ No extra dependency ❌ Boilerplate code ❌ Error-prone (miss fields) UserDto dto = new UserDto(); dto.setName(user.getName()); dto.setEmail(user.getEmail()); ⚡ MapStruct ✔ Compile-time generated code ✔ Clean & minimal ✔ High performance (no reflection) ❌ Initial setup required @Mapper(componentModel = "spring") public interface UserMapper { UserDto toDto(User user); } 🔄 Flow Request → DTO → Mapper → Entity → DB DB → Entity → Mapper → DTO → Response 📌 Rule of Thumb Small project → Manual is fine Medium/large project → Use MapStruct 👉 If you are preparing for Java backend interviews, connect & follow - I share short, practical backend concepts regularly. #SpringBoot #Java #BackendDevelopment #MapStruct #CleanCode #SoftwareEngineering #InterviewPrep
Manual vs MapStruct Mapping in Spring Boot
More Relevant Posts
-
When building scalable backend systems, we often deal with hierarchical data structures — think file systems, organization trees, menu structures, or nested API responses. That’s where the Composite Design Pattern shines. 💡 👉 It allows us to treat individual objects (leaf nodes) and groups of objects (composites) in the same way using a common interface. 💻 Why it matters in backend development: ✔ Simplifies handling of tree-like data structures ✔ Promotes clean, maintainable, and extensible code ✔ Reduces conditional logic when dealing with nested objects ✔ Aligns well with recursive operations (like traversals) 🧠 Real-world backend examples: File systems (Files & Folders) Organization hierarchy (Employee & Manager) Comment systems (Comments & Replies) Menu rendering in APIs ⚙️ Core Idea: Define a common interface (say Component) that both: Leaf (single object) Composite (group of objects) implement. This lets you write code like: component.operation(); …without worrying whether it's a single object or a collection. 🔥 Key takeaway: “Composite Pattern helps you build tree structures and treat individual and grouped objects uniformly.” Check it out - https://lnkd.in/gQQfhWJK As a Java backend developer, mastering patterns like Composite helps in writing clean architecture and scalable systems — something every production-grade application demands. #Java #BackendDevelopment #DesignPatterns #SystemDesign #LLD #CleanCode #SoftwareEngineering
To view or add a comment, sign in
-
-
📦 DTO vs Entity — A Small Concept That Makes a Big Difference When I started building APIs, I used to send Entity objects directly in responses… Big mistake ❌ Let’s understand the right approach 👇 👉 Entity Represents database table Directly mapped using JPA/Hibernate Contains full data structure 👉 DTO (Data Transfer Object) Used to send data between client & server Contains only required fields Improves security & performance 💡 Why not expose Entity directly? ❌ Exposes sensitive data (like passwords) ❌ Tight coupling with database structure ❌ Hard to manage changes 🚀 What I do now: ✔ Use Entity → for database ✔ Use DTO → for API request/response ✔ Convert using Mapper (manual / MapStruct) 🧠 Key Insight: Good backend design is about controlling what data you expose. Consistency in learning API design = cleaner & secure systems 💪 Are you using DTOs in your projects or still returning Entities? #Java #SpringBoot #DTO #BackendDevelopment #CleanCode #FullStackDeveloper
To view or add a comment, sign in
-
-
𝗪𝗲 𝗿𝗲𝗽𝗹𝗮𝗰𝗲𝗱 𝗚𝘂𝗮𝘃𝗮 𝗜𝗺𝗺𝘂𝘁𝗮𝗯𝗹𝗲𝗠𝗮𝗽 𝘄𝗶𝘁𝗵 𝗝𝗮𝘃𝗮 𝗠𝗮𝗽.𝗼𝗳. 𝗔𝗻𝗱 𝘁𝗵𝗲 𝘀𝘆𝘀𝘁𝗲𝗺 𝗯𝗿𝗼𝗸𝗲. 💥 The code still compiled ✅ Nothing looked suspicious 👀 It was a small refactor 🔧 But after the change, behavior was different. Tests started failing ❌ Output changed 📦 Part of the system behaved differently ⚠️ At first glance, this looked strange. We replaced one immutable map with another immutable map. So why did anything break? Because the system had a hidden dependency 🧠 It turned out part of our logic was relying on iteration order. Not explicitly. Not by design. Just implicitly, through how the map was being used. And that was the real problem. Nobody on the team expected that a map would become part of the behavior in that way 🤯 But it already had. So the issue was not just "Guava vs JDK". The issue was that we changed a piece of code without fully understanding what the surrounding system had started to depend on. The quick fix was simple: use LinkedHashMap and restore deterministic ordering ⚡ But the more interesting lesson was not about LinkedHashMap. The real lesson was this: When you replace something that looks equivalent, you may still be changing behavior. Same shape of API does not mean same semantics ❗ Same return type does not mean same guarantees ⚠️ And "it worked before" does not mean the dependency was valid. It may simply have been hidden. That is why before replacing a method, collection, or utility, it is worth understanding 2 things: 1️⃣ The behavior of the thing you are introducing 2️⃣ The behavior your system already depends on #java #springboot #backend #softwareengineering #refactoring #engineering #distributedsystems
To view or add a comment, sign in
-
-
🚀 08/04/26 — Stack Foundations: Balancing Parentheses with Precision Today was a productive session where I successfully implemented the Valid Parentheses (LeetCode 20) challenge. This problem is a fundamental exercise in using the Stack data structure to manage nested relationships and maintain order-based logic. 🧱 The Valid Parentheses Logic The goal is to determine if an input string containing (, ), {, }, [ and ] is valid based on whether every open bracket is closed by the correct type and in the correct order. The Stack Strategy: Pushing: As I iterate through the string, whenever I encounter an opening bracket—(, {, or [—I push it onto the stack. Popping and Matching: When I encounter a closing bracket, I first check if the stack is empty. If it is, the string is invalid. Otherwise, I pop the top element from the stack and compare it to the current closing bracket. Validation: If the brackets don't match (e.g., a ) following a {), the function immediately returns false. Final Check: After the loop finishes, the string is only valid if the stack is completely empty, ensuring all open brackets were properly closed. Complexity Metrics: Time Complexity: O(n) where n is the length of the string, as we perform a single linear pass. Space Complexity: O(n) in the worst case where the string contains only opening brackets, requiring them all to be stored in the stack. 📈 Consistency Report Coming off my 50-day streak milestone, today's focus on stacks feels like a solid pivot from the sliding window and array patterns I've been mastering recently. The logic used here is remarkably similar to the structural checks I used in the "String Search" and "Mountain Array" problems earlier this month, where maintaining a specific state across iterations was key. Huge thanks to Anuj Kumar (a.k.a CTO Bhaiya on YouTube) for the continuous inspiration. Every new data structure I master adds another layer to my problem-solving toolkit! My tested O(n) stack-based implementation is attached below! 📄👇 #DSA #Java #Stack #ValidParentheses #DataStructures #Complexity #Consistency #LearningInPublic #CTOBhaiya
To view or add a comment, sign in
-
-
🚀 Entity vs DTO vs ViewModel in ASP.NET Core — Don’t Mix Them Up If these three concepts are blurred in your codebase… problems usually follow: ⚠️ Accidental data exposure ⚠️ Tight coupling between API & database ⚠️ UI logic leaking into backend ⚠️ Painful refactoring Let’s simplify it 👇 🔹 Entity (Data / Domain Layer) Represents your database structure and is used by ORMs like EF Core. ✅ Characteristics: ✔ Mirrors database tables ✔ Contains all fields (including sensitive data) ✔ Includes navigation properties 🚫 Important: Never expose Entities directly through APIs Why? Because you tightly couple your API to your database and risk exposing internal or sensitive data. 🔹 DTO (Data Transfer Object) The contract between your backend and the outside world. ✅ Characteristics: ✔ Contains only required data ✔ No sensitive fields ✔ No business logic 🎯 Used for: • API requests & responses • Service-to-service communication 💡 Think of DTOs as a protective boundary around your domain. 🔹 ViewModel (Presentation Layer) Designed specifically for the UI layer ✅ Characteristics: ✔ UI-focused structure ✔ Validation rules ([Required], etc.) ✔ Computed / aggregated fields 📌 Examples: • FullName = FirstName + LastName • Dropdown lists • Form data 💡 Goal: Optimize the user experience — not the database 🔄 Clean Flow Database → Entity → DTO → ViewModel → UI Each layer has a clear responsibility. 🧠 Rule of Thumb 👉 Entity = Database 👉 DTO = Transport (API) 👉 ViewModel = UI 🎯 Common Mistakes ❌ Returning Entities directly from APIs ❌ Mixing UI logic into domain models ❌ Adding logic inside DTOs ✅ Why Separation Matters ✔ Better security (no data leaks) ✔ Loose coupling ✔ Cleaner, maintainable code ✔ Easier refactoring ✔ More professional architecture 📌 Bottom Line Separation isn’t overengineering — it’s what keeps your system scalable and maintainable. If you’re still exposing Entities in your controllers… it might be time to rethink your design 👀 #DotNet #ASPNetCore #CleanArchitecture #SoftwareEngineering #BackendDevelopment #BestPractices #Programming #WebDevelopment #CSharp
To view or add a comment, sign in
-
-
Every engineering team knows the tension: do you fix the architecture or ship the workaround? When our mocking library was deprecated, the "right" answer was probably a full-scale refactor to dependency injection across 13,000 Java files. The practical answer was a pattern our team hadn’t seen documented anywhere—singleton swapping. Brendan Boyd walks through the pattern, the tradeoffs, and why they were worth it. https://lnkd.in/gfrJpY26
To view or add a comment, sign in
-
📅 Date: May 1, 2026 Day 9 of my LeetCode Journey 🚀 ✅ Problem Solved: 20. Valid Parentheses 🧠 Approach & Smart Solution: To solve this classic string validation problem, I utilized the Stack data structure. The Last-In-First-Out (LIFO) principle of a stack makes it the absolute perfect tool for keeping track of opening and closing brackets in the correct order! • Pseudo-code: Initialize an empty Stack to hold characters. Loop through every character in the string: If the character is an opening bracket ('(', '{', '['), push it onto the stack. If it is a closing bracket: Check if the stack is empty. If it is, return false (no matching open bracket). Pop the top element from the stack. Check if the popped element correctly matches the current closing bracket. If it doesn't match, return false. After the loop, return true ONLY if the stack is completely empty (meaning all brackets were properly closed). This elegant approach ensures that nested and sequential brackets are validated efficiently in a single pass! ⏱️ Time Complexity: O(n) (Single pass through the string) 📦 Space Complexity: O(n) (In the worst case, all opening brackets are pushed onto the stack) 📊 Progress Update: • Streak: 8 Days 🔥 • Difficulty: Easy • Pattern: Stack / String Parsing 🔗 LeetCode Profile: https://lnkd.in/gBcDQwtb (@Hari312004) Mastering core data structures like Stacks is essential for writing compilers, parsers, and robust backend validations! 💡 #LeetCode #DSA #Stack #Java #CodingJourney #ProblemSolving #InterviewPrep #Consistency #BackendDevelopment
To view or add a comment, sign in
-
-
DTO is the new spaghetti. Fight me. 🍝 It used to be simple: Client → Controller → Service → DB And that was enough. But now? • DTO Request • DTO Response • Mapper there • Mapper back • Entity on the side • And all of this for… the exact same data 0 new logic. 5 transformations. We’ve learned to: - overcomplicate simple things - abstract without a reason - add layers “just in case” And somehow this is called “clean architecture”. ❓The real question: Are you actually solving business problems or just moving data between objects? My hot take: 👉 In 80% of projects, DTOs are not architecture - they’re a ritual 👉 Mappers hide problems more often than they solve them 👉 “Layer isolation” turns into isolation from meaning Yes, there are cases where DTOs make sense. But let’s be honest: How many of your DTOs actually do something, instead of just copying fields? 🔥 Ready for the debate: - When did DTOs actually save your project? - When did you remove them and things got better? - Or are you still writing a mapper for every sneeze? Let’s go 👇 #softwarearchitecture #cleanarchitecture #backenddevelopment #systemdesign #coding #programming #java #springboot #microservices #ddd #oop #refactoring #techdebt #engineering #devlife #bestpractices #antipatterns #softwareengineering #developerlife #architecture
To view or add a comment, sign in
-
-
This one will make a lot of backend engineers uncomfortable. DTOs are useful when they protect real boundaries. They are not useful when they exist only because “that is what clean architecture is supposed to look like.” That is the point where engineering quietly turns into ritual. More abstraction does not always mean better design. Sometimes it just means more mapping, more indirection, and less understanding. The real question is simple: does this layer reduce complexity, or just spread it around? 🤔 Curious how others see it: where do DTOs genuinely protect the design, and where do they just create noise?
DTO is the new spaghetti. Fight me. 🍝 It used to be simple: Client → Controller → Service → DB And that was enough. But now? • DTO Request • DTO Response • Mapper there • Mapper back • Entity on the side • And all of this for… the exact same data 0 new logic. 5 transformations. We’ve learned to: - overcomplicate simple things - abstract without a reason - add layers “just in case” And somehow this is called “clean architecture”. ❓The real question: Are you actually solving business problems or just moving data between objects? My hot take: 👉 In 80% of projects, DTOs are not architecture - they’re a ritual 👉 Mappers hide problems more often than they solve them 👉 “Layer isolation” turns into isolation from meaning Yes, there are cases where DTOs make sense. But let’s be honest: How many of your DTOs actually do something, instead of just copying fields? 🔥 Ready for the debate: - When did DTOs actually save your project? - When did you remove them and things got better? - Or are you still writing a mapper for every sneeze? Let’s go 👇 #softwarearchitecture #cleanarchitecture #backenddevelopment #systemdesign #coding #programming #java #springboot #microservices #ddd #oop #refactoring #techdebt #engineering #devlife #bestpractices #antipatterns #softwareengineering #developerlife #architecture
To view or add a comment, sign in
-
-
𝗠𝗮𝘀𝘁𝗲𝗿 𝗝𝗮𝘃𝗮𝗦𝗰𝗿𝗶𝗽𝘁 𝗗𝗲𝘀𝘁𝗿𝘂𝗰𝘁𝘂𝗿𝗶𝗻𝗴 Stop writing repetitive code to get data from arrays or objects. Destructuring grabs values in one line. Arrays use position. Old way: const scores = [85, 92, 78] const first = scores[0] New way: const [first, second, third] = [85, 92, 78] Objects use property names. Old way: const user = { name: 'Ritam', age: 20 } const name = user.name New way: const { name, age } = user Rename variables on the fly. const { oldName: newName } = user Set default values for missing data. const { theme = 'light' } = config Use it in functions to clean up arguments. function greet({ name, age }) { console.log(name, age) } Benefits: - Less repetitive code. - Better readability. - Fewer errors with defaults. This is a mindset shift for cleaner code. Use it in your Node.js or React projects. Source: https://lnkd.in/gZthht7g
To view or add a comment, sign in
Explore related topics
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