Bird
Raised Fist0
Spring Bootframework~20 mins

DTO vs entity separation benefit in Spring Boot - Practice Questions

Choose your learning style10 modes available

Start learning this pattern below

Jump into concepts and practice - no test required

or
Recommended
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Challenge - 5 Problems
🎖️
DTO vs Entity Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
🧠 Conceptual
intermediate
2:00remaining
Why separate DTOs from entities in Spring Boot?
In a Spring Boot application, why is it beneficial to separate Data Transfer Objects (DTOs) from entity classes?
ABecause entities cannot be serialized to JSON
BTo reduce the number of classes in the project
CTo protect the database schema from direct exposure and allow flexible API evolution
DBecause DTOs automatically handle database transactions
Attempts:
2 left
💡 Hint
Think about how exposing entities directly might affect your API and database design.
component_behavior
intermediate
2:00remaining
What happens if you expose entities directly in API responses?
Consider a Spring Boot REST API that returns entity objects directly as JSON responses. What is a likely consequence of this approach?
AEntities will be converted to DTOs automatically by Spring Boot
BThe API will automatically validate all input data
CThe application will run faster due to fewer classes
DClients may receive sensitive or unnecessary data fields tied to the database schema
Attempts:
2 left
💡 Hint
Think about what data entities contain and how that might affect clients.
state_output
advanced
2:30remaining
What is the output when mapping entity to DTO with missing fields?
Given an entity with fields 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?
Spring Boot
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)
A{"id":1,"name":"Alice"}
B{"id":1,"name":"Alice","password":"secret"}
C{"name":"Alice"}
D{"id":1,"password":"secret"}
Attempts:
2 left
💡 Hint
Only fields declared in the DTO will be serialized in the JSON response.
📝 Syntax
advanced
2:00remaining
Identify the correct DTO mapping syntax in Spring Boot
Which of the following code snippets correctly maps a UserEntity to a UserDTO in Spring Boot using a constructor?
Spring Boot
public record UserEntity(Long id, String name, String password) {}
public record UserDTO(Long id, String name) {}
AUserDTO dto = new UserDTO(userEntity.id, userEntity.name);
BUserDTO dto = new UserDTO(userEntity.id(), userEntity.name());
CUserDTO dto = new UserDTO(userEntity.getId(), userEntity.getName());
DUserDTO dto = new UserDTO(userEntity.getId, userEntity.getName);
Attempts:
2 left
💡 Hint
Records use accessor methods without 'get' prefix.
🔧 Debug
expert
3:00remaining
Why does exposing entities cause a security risk in Spring Boot?
A developer returns JPA entity objects directly from a REST controller. Later, they notice sensitive fields like passwords are exposed in API responses. Why does this happen?
AEntities include all fields by default, so sensitive data is serialized unless explicitly excluded
BDTOs are required to serialize entities properly
CSpring Boot automatically encrypts entity fields, so passwords are safe
DEntities cannot be serialized to JSON, so this is impossible
Attempts:
2 left
💡 Hint
Think about what happens when an object is converted to JSON without filtering.

Practice

(1/5)
1. Why is it beneficial to separate DTOs from entities in a Spring Boot application?
easy
A. It allows direct modification of database tables from the UI.
B. It makes the application run faster by skipping database calls.
C. It keeps the database structure hidden and improves security.
D. It reduces the number of classes in the project.

Solution

  1. Step 1: Understand the role of entities

    Entities represent the database structure and are tightly linked to how data is stored.
  2. Step 2: Understand the role of DTOs

    DTOs are used to transfer data safely between layers or systems, hiding internal details.
  3. Final Answer:

    It keeps the database structure hidden and improves security. -> Option C
  4. Quick Check:

    DTOs separate data transfer from entities = A [OK]
Hint: DTOs hide database details from outside layers [OK]
Common Mistakes:
  • Thinking DTOs speed up database calls
  • Believing entities should be exposed directly
  • Confusing DTOs with database tables
2. Which of the following is the correct way to define a DTO class in Spring Boot?
easy
A. public class UserDTO { private String name; public String getName() { return name; } }
B. public record UserDTO(String name) {}
C. public enum UserDTO { NAME; }
D. public interface UserDTO { String name; }

Solution

  1. Step 1: Review DTO class options

    DTOs are simple data carriers. Java records provide a concise way to define immutable DTOs.
  2. Step 2: Identify the correct syntax

    public record UserDTO(String name) {} uses a record, which is modern and recommended for DTOs in Java 17+.
  3. Final Answer:

    public record UserDTO(String name) {} -> Option B
  4. Quick Check:

    Use records for simple DTOs = D [OK]
Hint: Use Java records for simple DTOs in Spring Boot [OK]
Common Mistakes:
  • Using interfaces without methods for DTOs
  • Using enums instead of classes or records
  • Not providing getters for DTO fields
3. Given this code snippet, what will be the output when converting an entity to a DTO?
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());
medium
A. Alice
B. null
C. Compilation error
D. Empty string

Solution

  1. Step 1: Understand entity to DTO conversion

    The entity has a name "Alice" which is passed to the DTO constructor.
  2. Step 2: Check the output of dto.name()

    Since dto stores "Alice", printing dto.name() outputs "Alice".
  3. Final Answer:

    Alice -> Option A
  4. Quick Check:

    Entity name passed to DTO = Alice [OK]
Hint: DTO fields hold entity data passed in constructor [OK]
Common Mistakes:
  • Assuming dto.name() returns null
  • Confusing record syntax causing errors
  • Expecting entity and DTO to be the same object
4. Identify the problem in this code snippet that mixes entity and DTO responsibilities:
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 + "\"}"; }
}
medium
A. The toJson method should return XML instead.
B. Getter and setter methods are missing.
C. The name field should be public.
D. Entity class should not handle JSON formatting.

Solution

  1. Step 1: Analyze entity responsibilities

    Entities should focus on data storage and mapping, not formatting or presentation.
  2. Step 2: Identify separation violation

    toJson mixes data with presentation logic, which belongs in DTO or service layers.
  3. Final Answer:

    Entity class should not handle JSON formatting. -> Option D
  4. Quick Check:

    Keep entity and presentation separate = A [OK]
Hint: Entities store data; DTOs handle data format [OK]
Common Mistakes:
  • Allowing entities to format output
  • Making entity fields public
  • Confusing DTO and entity roles
5. You have a UserEntity with sensitive fields like password and internal IDs. How does using a separate UserDTO improve your Spring Boot API's security and maintainability?
hard
A. By exposing only necessary fields and hiding sensitive data from API responses.
B. By allowing direct database updates from the API without validation.
C. By merging all entity fields into one large DTO for simplicity.
D. By removing the need for service layers in the application.

Solution

  1. Step 1: Recognize sensitive data risks

    Entities contain all data, including sensitive info like passwords, which should not be exposed.
  2. Step 2: Understand DTO role in security

    DTOs can include only safe fields, preventing accidental exposure in API responses.
  3. Step 3: Consider maintainability benefits

    Separating DTOs allows easier changes to API without affecting database structure.
  4. Final Answer:

    By exposing only necessary fields and hiding sensitive data from API responses. -> Option A
  5. Quick Check:

    DTOs protect sensitive data and ease maintenance = B [OK]
Hint: DTOs hide sensitive entity fields from API output [OK]
Common Mistakes:
  • Exposing all entity fields directly
  • Skipping validation by merging DTO and entity
  • Removing service layers causing tight coupling