Jānis Ošs’ Post

🚀 DTO Pattern in Spring Boot — Stop Exposing Your Entities! One of the most common mistakes junior Java developers make is returning JPA entities directly from REST controllers. Here's why DTOs will save your application architecture. What is a DTO? A Data Transfer Object is a simple POJO used to carry data between layers — decoupling your API contract from your database model. // ❌ BAD: Exposing entity directly @GetMapping("/users/{id}") public User getUser(@PathVariable Long id) { return userRepository.findById(id).orElseThrow(); } // ✅ GOOD: Using DTO @GetMapping("/users/{id}") public UserResponseDto getUser(@PathVariable Long id) { User user = userRepository.findById(id).orElseThrow(); return mapper.toDto(user); } MapStruct makes this effortless — it generates mapping code at compile time with zero reflection overhead: @Mapper(componentModel = "spring") public interface UserMapper { UserResponseDto toDto(User user); User toEntity(CreateUserRequestDto dto); } Benefits: hide sensitive fields (passwords!), shape your API independently of DB schema, and reduce serialization issues with lazy-loaded relations. #Java #SpringBoot #BackendDevelopment #DTO #MapStruct #CleanCode #SoftwareEngineering

Could you please elaborate on the lazy loading part?

Like
Reply

To view or add a comment, sign in

Explore content categories