🚀 Stop exposing your Entity directly in APIs. It works… but it’s a bad practice. Let’s understand why 👇 --- 👉 What most beginners do: @GetMapping("/users") public List<User> getUsers() { return userRepository.findAll(); // ❌ returning Entity directly } --- ❌ Problems: - Exposes internal DB structure - Sends unwanted fields (password, internal IDs) - Tight coupling between DB & API --- ✅ Better approach → Use DTO (Data Transfer Object) @GetMapping("/users") public List<UserDTO> getUsers() { return userService.getUsers(); // ✅ returns DTO } --- 💡 What is DTO? A simple object used to transfer only required data. Example: public class UserDTO { private String name; private String email; } --- 🔥 Why DTO is important: ✔ Hides sensitive data ✔ Controls API response ✔ Decouples DB from API ✔ Makes system scalable --- ⚡ Real-world example: Entity: User { id, name, email, password } DTO: UserDTO { name, email } 👉 Password is never exposed 🚀 --- ❌ Common mistake: Using Entity everywhere → works initially But becomes risky in production --- 📌 Key Takeaway: Entity = Database structure DTO = API contract Never mix them. --- Follow for more real backend learnings 🚀 #SpringBoot #Java #BackendDevelopment #CleanCode #SoftwareEngineer
Avoid Exposing Entities in APIs with DTOs
More Relevant Posts
-
🚀 Most REST APIs work… but very few are well-designed. If you follow these practices, your APIs become production-ready 👇 --- 👉 1️⃣ Use proper HTTP methods GET → Fetch data POST → Create PUT → Update (full) PATCH → Update (partial) DELETE → Remove ❌ Don’t use POST for everything --- 👉 2️⃣ Use meaningful URLs ❌ /getUserData ✅ /users/{id} ❌ /createOrder ✅ POST /orders --- 👉 3️⃣ Use correct status codes 200 → Success 201 → Created 400 → Bad request 404 → Not found 500 → Server error 👉 Status codes = communication with client --- 👉 4️⃣ Don’t expose internal data ❌ Return Entity directly ✅ Use DTO --- 👉 5️⃣ Handle errors properly ❌ return null ✅ Use Global Exception Handling --- 👉 6️⃣ Version your APIs ✅ /api/v1/users 👉 Helps when you update APIs later --- 👉 7️⃣ Keep responses consistent { "status": "success", "data": {...}, "message": "User fetched successfully" } --- ⚡ Real-world impact: Bad API: ❌ Confusing ❌ Hard to maintain Good API: ✅ Easy to use ✅ Scalable ✅ Professional --- 📌 Key Takeaway: Good APIs are not just working APIs… They are clean, consistent, and predictable. --- Follow for more real backend learnings 🚀 #SpringBoot #Java #BackendDevelopment #APIDesign #SoftwareEngineer
To view or add a comment, sign in
-
-
An API issue that wasn’t actually an API problem… Recently, I faced a production issue where an API response was taking much longer than expected. At first, everything pointed towards the API layer: - Code looked clean - No exceptions - No obvious bottlenecks But users were still experiencing delays… So I started digging deeper 👇 ✔️ Checked API logs → all good ✔️ Verified business logic → no issue ✔️ Then analyzed database queries And that’s where the real problem was. A poorly optimized SQL query was slowing down the entire response. Even though the API was working perfectly, it was dependent on inefficient data retrieval. 🔍 Fix: - Optimized the SQL query - Added proper indexing - Removed unnecessary joins ⚡ Result: Response time improved drastically 🚀 💡 Lesson: In backend systems, API performance is only as good as your database performance. Working on real systems taught me one thing: Issues are rarely where they appear. Still learning and improving every day as a backend engineer 💻 👉 Have you faced a situation where the issue was somewhere else than expected? #BackendDevelopment #DotNet #SQL #API #SoftwareEngineering #ProductionIssues #TechLearning
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
-
-
💡 Using @Transactional in a GET API — Do You Really Need It? Most developers think @Transactional is only for INSERT/UPDATE/DELETE operations… but what about GET APIs? 🤔 Let’s break it down in the simplest way possible 👇 ⸻ 🔹 What does @Transactional do? It tells Spring: 👉 “Wrap this method in a database transaction.” That means: • All DB operations inside run safely • Either everything succeeds OR everything rolls back ⸻ 🔹 But GET API only reads data… why use it? Good question 👍 Even in read operations, @Transactional can be useful in some cases: ⸻ ✅ 1. To Avoid Lazy Loading Errors If you’re using JPA/Hibernate and fetching related data (like user.getOrders()), you might face: ❌ LazyInitializationException 👉 Why? Because the DB session is already closed. 💡 Solution: Using @Transactional keeps the session open while data is being fetched. ⸻ ✅ 2. To Ensure Consistent Data Imagine: • You are reading multiple tables • Data is changing at the same time Without transaction: 👉 You might get inconsistent results With @Transactional: 👉 You get a consistent snapshot of data ⸻ ✅ 3. For Better Performance (Read-Only Mode) You can write: @Transactional(readOnly = true) 👉 This tells the database: • “I’m only reading data, not modifying it” ⚡ Result: • Better performance • Less overhead ⸻ ⚠️ When NOT to use it? Don’t blindly add it to every GET API ❌ Avoid if: • Simple single-table fetch • No lazy loading • No complex logic 👉 Because transactions also add overhead ⸻ 🔥 Simple Rule to Remember: ✔ Complex read → Use @Transactional(readOnly = true) ❌ Simple read → Skip it ⸻ 🧠 Final Thought @Transactional is not just for writing data — it’s about managing how you interact with the database safely and efficiently. ⸻ #Java #SpringBoot #BackendDevelopment #CodingTips #Developers #TechSimplified
To view or add a comment, sign in
-
🧠 A follow-up on REST API design (and a common hidden issue) In a previous post, I mentioned why returning entities directly from the database can cause problems. One of the most common (and frustrating) ones in Spring-based applications is: ⚠️ LazyInitializationException This usually happens when: You expose entities directly You rely on ORM (like JPA/Hibernate) And a lazy relationship is accessed outside of a transaction 🚨 Suddenly, your API breaks… or you start adding quick fixes like: Changing relationships to EAGER Adding Open Session in View (OSIV) Forcing unnecessary queries 👉 All of these can hurt performance and scalability. 🚀 An alternative worth considering: Spring Data JDBC Instead of relying on a full ORM, Spring Data JDBC follows a simpler approach: No lazy loading No proxies No hidden queries You explicitly control what gets loaded. 💡 Why this can be powerful (especially in microservices): ✅ Predictable queries (what you load is what you get) ✅ Better performance (no unexpected joins or N+1 issues) ✅ Simpler mental model (less ORM magic) ✅ Fits well with small, focused microservices 🧠 In many cases, combining: DTOs for API responses Explicit data loading (instead of lazy ORM behavior) …can make your services more robust, faster, and easier to maintain. #Java #SpringBoot #Microservices #BackendDevelopment #SoftwareEngineering
To view or add a comment, sign in
-
Built a clean backend API with proper structure ------------------------------------------------------------------------------------ After learning and practicing, I created my backend using a clear flow Client -> Routes -> Middleware -> DTO using Joi -> Controller -> Service -> Model -> Database **Project structure** controllers -> handle request and response services -> business logic models -> database schema routes -> API endpoints middleware -> validation and auth dtos -> Joi validation schemas **Key points** Used Joi for validation instead of manual checks Created reusable validation middleware Kept controllers clean and simple Moved logic to service layer Connected to MongoDB Atlas Tested using Postman POST /register -> sent data -> validated -> stored in database This helped me understand how real backend systems are built Would love to know what I should learn next #NodeJS #ExpressJS #MongoDB #Backend #WebDevelopment #Learning#chaiAurCode
To view or add a comment, sign in
-
Day 31. My API worked perfectly. Until real data hit it. In development, everything looked clean. → Small dataset → Fast responses → No errors I thought I was done. Then I tested it with real data. That’s when things changed. → API became slow → Queries increased → Response time jumped → Unexpected behavior appeared Nothing was broken. But everything felt wrong. That’s when it clicked. Your code doesn’t fail in development. It fails under real conditions. What worked with 10 records didn’t work with 10,000. So I started paying attention to: → Query count → Data size → Response time → Edge cases What I learned: → Small data hides big problems → Performance issues don’t throw errors → Real testing > perfect code The hard truth: → If you don’t test with real data → You don’t really know your system Writing code is step one. Understanding how it behaves at scale is step two. What’s the sneakiest bug real data ever revealed in your code? 👇 Drop it below #SpringBoot #Java #BackendDevelopment #Performance #BuildInPublic #JavaDeveloper
To view or add a comment, sign in
-
Over the past few days, I’ve been diving deep into how JPA and Spring Data JPA handle database interactions — and honestly, understanding the internals changed how I look at backend systems. Here are 3 core building blocks that clicked for me: 🔹 DataSource The foundation that provides database connections (driver, URL, credentials). Without it, nothing talks to the database. 🔹 EntityManagerFactory A heavyweight, thread-safe factory that bootstraps JPA and creates EntityManager instances. Think of it as the control center of persistence. 🔹 EntityManager The workhorse that manages the persistence context, handles CRUD operations, and interacts with the database. Not thread-safe — so each transaction gets its own instance. Behind every @Transactional annotation, there’s a powerful orchestration happening: 🔹Transaction Manager ensures commit/rollback 🔹Persistence Context tracks entity states (new, managed, detached, removed) 🔹PlatformTransactionManager abstracts everything across technologies #Java #SpringBoot #JPA #BackendDevelopment #FullStackDeveloper #Microservices #SystemDesign #HappyLearning #DeveloperLife #SoftwareEngineering #Coding
To view or add a comment, sign in
-
-
Day 14. My API worked perfectly. Until it hit 100 users. I had this: List<Order> orders = orderRepository.findAll(); for (Order order : orders) { System.out.println(order.getUser().getName()); } Because of queries I didn’t even know existed. Looks clean. It’s not. Here’s what was actually happening: → 1 query to fetch all orders → 1 query per order to fetch the user → 100 orders = 101 queries hitting your database That’s the N+1 problem. And it hides in plain sight. Your code looks clean. Your database is suffering. And you probably have this in your codebase right now. The fix is simple: Fetch what you need. In one query. @Query("SELECT o FROM Order o JOIN FETCH o.user") List<Order> findAllWithUser(); One query. One JOIN. Everything loaded together. What actually changes: → Performance — 101 queries becomes 1 → Scalability — works at 100 rows, breaks at 100,000 → Visibility — you won’t notice until production The hard truth: → ORMs make it easy to write slow code → Lazy loading is convenient until it isn’t → You need to know what SQL your code is generating Writing code that works is easy. Writing code that doesn’t silently destroy your database is the real skill. Are you logging your SQL queries in development? If not — you should be. 👇 Drop it below #SpringBoot #Java #Hibernate #BackendDevelopment #JavaDeveloper
To view or add a comment, sign in
-
🧬 Spring Boot – Understanding DTO (Data Transfer Object) Yesterday I explored one of the most important concepts in backend development — DTO. 🧠 Key Learnings: ✔️ DTO is used to transfer data between client ↔ server ✔️ It contains only required fields (no unnecessary or sensitive data) ✔️ Acts as a safe layer between API and database 💡 Why not expose Entity directly? Entities represent database structure and may contain sensitive data like passwords ❌ Exposing them directly can lead to security risks and poor API design ✅ Using DTO helps with: • Security – hides sensitive fields • Clean APIs – sends only required data • Decoupling – DB changes won’t affect API • Better control over request/response 🔁 Flow in real applications: Client → DTO → Controller → Service → Entity → Database Database → Entity → Service → DTO → Client 💻DSA Practice: • Palindrome number check • Sum of digits 🚀 This concept is widely used in real-world projects and microservices architecture. Understanding DTO is a big step towards writing secure and scalable backend applications. #SpringBoot #Java #BackendDevelopment #Microservices #DTO #SoftwareEngineering #LearningInPublic
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