Separating DTOs from entities helps protect the internal database structure from external clients. It also allows the API to evolve independently without changing the database schema.
Entities often contain fields that should not be exposed externally, such as internal IDs or audit information. Returning entities directly can leak this data.
id, name, and password, and a DTO with only id and name, what will be the output JSON when mapping the entity to the DTO and returning it in a Spring Boot REST controller?public record UserEntity(Long id, String name, String password) {}
public record UserDTO(Long id, String name) {}
// Mapping method
public UserDTO toDTO(UserEntity entity) {
return new UserDTO(entity.id(), entity.name());
}
// Controller method returns toDTO(userEntity)The DTO only contains id and name, so the JSON output excludes password. This protects sensitive data from being exposed.
public record UserEntity(Long id, String name, String password) {}
public record UserDTO(Long id, String name) {}Java records provide accessor methods named after the fields, so userEntity.id() and userEntity.name() are correct.
Entities contain all fields, including sensitive ones. Without DTOs or annotations to exclude fields, all data is serialized and sent to clients, causing security risks.
