What if your app accidentally shared secret data just because you skipped a simple step?
DTO vs entity separation benefit in Spring Boot - When to Use Which
Start learning this pattern below
Jump into concepts and practice - no test required
Imagine building a web app where you directly send your database objects to users without any filtering or changes.
You want to add new fields or hide sensitive info, but every change risks breaking your app or exposing data.
Using database entities directly for data transfer is risky and messy.
It mixes database logic with what users see, making updates complicated and error-prone.
It also exposes sensitive data unintentionally and makes testing harder.
Separating DTOs (Data Transfer Objects) from entities keeps your data safe and your code clean.
DTOs act like a filtered window, showing only what users need.
This separation makes your app easier to maintain, test, and evolve without breaking things.
return userRepository.findById(id); // returns Optional<User> entity directlyUserDTO dto = userMapper.toDTO(userRepository.findById(id).orElse(null)); // returns safe DTO
This separation enables secure, clear, and flexible data exchange between your app and users.
Think of an online store: you keep full product details in your database but only send name, price, and image to customers, hiding internal costs or supplier info.
Directly exposing entities mixes concerns and risks data leaks.
DTOs provide a safe, tailored view of data for users.
Separating them improves security, maintainability, and clarity.
Practice
Solution
Step 1: Understand the role of entities
Entities represent the database structure and are tightly linked to how data is stored.Step 2: Understand the role of DTOs
DTOs are used to transfer data safely between layers or systems, hiding internal details.Final Answer:
It keeps the database structure hidden and improves security. -> Option CQuick Check:
DTOs separate data transfer from entities = A [OK]
- Thinking DTOs speed up database calls
- Believing entities should be exposed directly
- Confusing DTOs with database tables
Solution
Step 1: Review DTO class options
DTOs are simple data carriers. Java records provide a concise way to define immutable DTOs.Step 2: Identify the correct syntax
public record UserDTO(String name) {} uses a record, which is modern and recommended for DTOs in Java 17+.Final Answer:
public record UserDTO(String name) {} -> Option BQuick Check:
Use records for simple DTOs = D [OK]
- Using interfaces without methods for DTOs
- Using enums instead of classes or records
- Not providing getters for DTO fields
record UserDTO(String name) {}
class UserEntity { String name; UserEntity(String name) { this.name = name; } }
UserEntity entity = new UserEntity("Alice");
UserDTO dto = new UserDTO(entity.name);
System.out.println(dto.name());Solution
Step 1: Understand entity to DTO conversion
The entity has a name "Alice" which is passed to the DTO constructor.Step 2: Check the output of dto.name()
Since dto stores "Alice", printing dto.name() outputs "Alice".Final Answer:
Alice -> Option AQuick Check:
Entity name passed to DTO = Alice [OK]
- Assuming dto.name() returns null
- Confusing record syntax causing errors
- Expecting entity and DTO to be the same object
public class UserEntity {
private String name;
public String getName() { return name; }
public void setName(String name) { this.name = name; }
public String toJson() { return "{\"name\":\"" + name + "\"}"; }
}Solution
Step 1: Analyze entity responsibilities
Entities should focus on data storage and mapping, not formatting or presentation.Step 2: Identify separation violation
toJson mixes data with presentation logic, which belongs in DTO or service layers.Final Answer:
Entity class should not handle JSON formatting. -> Option DQuick Check:
Keep entity and presentation separate = A [OK]
- Allowing entities to format output
- Making entity fields public
- Confusing DTO and entity roles
Solution
Step 1: Recognize sensitive data risks
Entities contain all data, including sensitive info like passwords, which should not be exposed.Step 2: Understand DTO role in security
DTOs can include only safe fields, preventing accidental exposure in API responses.Step 3: Consider maintainability benefits
Separating DTOs allows easier changes to API without affecting database structure.Final Answer:
By exposing only necessary fields and hiding sensitive data from API responses. -> Option AQuick Check:
DTOs protect sensitive data and ease maintenance = B [OK]
- Exposing all entity fields directly
- Skipping validation by merging DTO and entity
- Removing service layers causing tight coupling
