In a Spring Boot app, what is the main reason to use Data Transfer Objects (DTOs)?
Think about how you protect your private information when sharing only what is needed.
DTOs act like a filter between your database entities and the outside world. They help keep internal details private and allow you to change your database without breaking clients.
Consider a Spring Boot REST controller that returns JPA entities directly as JSON. What is a likely problem?
Think about what happens when you share your full address book with everyone, including private notes.
Returning entities directly can expose sensitive data and cause serialization problems like infinite loops when entities reference each other.
Given the following code snippet, what JSON will the client receive?
public record UserEntity(Long id, String username, String password) {}
public record UserDTO(Long id, String username) {}
@GetMapping("/user/{id}")
public UserDTO getUser(@PathVariable Long id) {
UserEntity user = userService.findById(id);
return new UserDTO(user.id(), user.username());
}Look at which fields the DTO includes compared to the entity.
The DTO only includes id and username, so the password is not sent to the client.
Choose the correct Java code that converts a UserEntity to a UserDTO.
Remember the DTO only has id and username fields.
Option C correctly passes the two required fields. Options B, C, and D either pass wrong number of arguments or include password which DTO does not have.
Given two JPA entities User and Address with bidirectional @OneToMany and @ManyToOne relationships, returning User directly from a REST controller causes a StackOverflowError. Why?
Think about what happens when you look in a mirror facing another mirror.
The circular references between User and Address cause the JSON serializer to recurse infinitely, leading to StackOverflowError.