Optimize Spring Boot API Performance with DTOs and Projections

Not every API should return Entity objects. Spring Boot experts use DTOs and Projections for read performance. Most developers do this: @GetMapping("/users") public List<User> getUsers() { return userRepository.findAll(); } It works… but it’s not optimal. ⸻ ❌ Problem Returning Entity: • Loads unnecessary fields • Fetches relationships lazily • Slower response • Tight coupling with DB ⸻ 🧠 Better Option 1 — DTO public class UserDto { private String name; private String email; } Mapping: return users.stream() .map(user -> new UserDto( user.getName(), user.getEmail())) .toList(); ⸻ ⚡ Best Option — Projection (Expert Way) Spring Boot supports interface-based projections: public interface UserProjection { String getName(); String getEmail(); } Repository: List<UserProjection> findAllProjectedBy(); Only required fields are fetched. ⸻ 💡 When to Use Use Entity → write operations Use DTO → API responses Use Projection → read-only optimized queries ⸻ 🧠 Expert Rule Write APIs for write flexibility Read APIs for performance ⸻ Day 18 of becoming production-ready with Spring Boot. Question: Do you use DTO or Projection for read APIs? ⸻ #Java #SpringBoot #BackendEngineering #Performance #SoftwareArchitecture

  • No alternative text description for this image

interface projections are underused and they give massive performance gains since Hibernate generates SELECT with only the needed columns. for write vs read API separation we use CQRS-lite where command endpoints use entities and query endpoints use projections. MapStruct for DTO mapping is also worth checking out

To view or add a comment, sign in

Explore content categories