Bird
Raised Fist0
Spring Bootframework~20 mins

Nested DTOs in Spring Boot - Practice Problems & Coding Challenges

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
🎖️
Nested DTO Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
component_behavior
intermediate
2:00remaining
What is the output of this nested DTO serialization?
Given the following Spring Boot DTO classes and a controller returning a nested DTO, what JSON will be returned to the client?
Spring Boot
public record AddressDTO(String street, String city) {}

public record UserDTO(String name, AddressDTO address) {}

@RestController
public class UserController {
    @GetMapping("/user")
    public UserDTO getUser() {
        AddressDTO address = new AddressDTO("123 Main St", "Springfield");
        return new UserDTO("John Doe", address);
    }
}
A{"name":"John Doe","address":null}
B{"name":"John Doe","address":"123 Main St, Springfield"}
C{"name":"John Doe","address":{"street":"123 Main St","city":"Springfield"}}
D{"name":"John Doe","address":{"street":"123 Main St"}}
Attempts:
2 left
💡 Hint
Think about how nested records are serialized by default in Spring Boot with Jackson.
state_output
intermediate
1:30remaining
What is the value of the nested DTO field after mapping?
Consider these DTOs and a mapping method that creates a nested DTO. What is the value of userDTO.address.city after calling mapToUserDTO()?
Spring Boot
public record AddressDTO(String street, String city) {}
public record UserDTO(String name, AddressDTO address) {}

public UserDTO mapToUserDTO() {
    AddressDTO address = new AddressDTO("456 Elm St", "Metropolis");
    return new UserDTO("Alice", address);
}
A"Metropolis"
B"456 Elm St"
Cnull
D"Alice"
Attempts:
2 left
💡 Hint
Remember the nested DTO stores city as a separate field.
📝 Syntax
advanced
2:30remaining
Which option correctly defines a nested DTO with Lombok in Spring Boot?
You want to create nested DTOs using Lombok annotations. Which code snippet correctly defines UserDTO with a nested AddressDTO?
A
@Data public class UserDTO { private String name; private AddressDTO address; }
@Data public class AddressDTO { private String street; private String city; }
B
@Data public class UserDTO { private String name; private String address; }
@Data public class AddressDTO { private String street; private String city; }
C
@Data public class UserDTO { private String name; private AddressDTO address; }
@Data public class AddressDTO { private String street; }
D
@Data public class UserDTO { private String name; private AddressDTO address; }
@Data public class AddressDTO { private String city; }
Attempts:
2 left
💡 Hint
Nested DTOs require matching fields in both classes.
🔧 Debug
advanced
3:00remaining
Why does this nested DTO cause a JSON serialization error?
Given these DTOs, the controller returns UserDTO but the JSON response fails. What is the cause?
Spring Boot
public class AddressDTO {
    private String street;
    private String city;
    // no getters or setters
}

public class UserDTO {
    private String name;
    private AddressDTO address;
    // getters and setters only for name
}

@RestController
public class UserController {
    @GetMapping("/user")
    public UserDTO getUser() {
        AddressDTO address = new AddressDTO();
        address.street = "789 Oak St";
        address.city = "Gotham";
        UserDTO user = new UserDTO();
        user.setName("Bruce");
        user.setAddress(address);
        return user;
    }
}
AAddressDTO fields are private but should be public for serialization.
BAddressDTO lacks getters, so Jackson cannot serialize its fields.
CUserDTO is missing a no-args constructor causing deserialization failure.
DUserDTO's name field is missing a setter causing serialization error.
Attempts:
2 left
💡 Hint
Jackson needs getters to read private fields during serialization.
🧠 Conceptual
expert
3:30remaining
How does Spring Boot handle nested DTOs with circular references during JSON serialization?
Consider two nested DTOs referencing each other, causing a circular reference. What is the default behavior of Spring Boot's JSON serialization, and how can it be resolved?
ASpring Boot returns null for one of the nested objects to prevent loops.
BSpring Boot automatically detects and ignores circular references without errors.
CSpring Boot serializes both objects fully, duplicating data infinitely.
DSpring Boot throws a StackOverflowError by default; use @JsonManagedReference and @JsonBackReference to fix.
Attempts:
2 left
💡 Hint
Think about how Jackson handles circular references by default.

Practice

(1/5)
1. What is the main purpose of using Nested DTOs in Spring Boot applications?
easy
A. To handle HTTP requests without controllers
B. To group related data inside other data objects for better structure
C. To replace entity classes with simpler objects
D. To improve database query performance automatically

Solution

  1. Step 1: Understand DTO role

    DTOs (Data Transfer Objects) are used to carry data between processes or layers.
  2. Step 2: Identify Nested DTO purpose

    Nested DTOs group related data inside other DTOs to represent complex data structures clearly.
  3. Final Answer:

    To group related data inside other data objects for better structure -> Option B
  4. Quick Check:

    Nested DTOs = Group related data [OK]
Hint: Nested DTOs organize data inside other objects [OK]
Common Mistakes:
  • Thinking nested DTOs improve database speed
  • Confusing DTOs with entities
  • Assuming nested DTOs replace controllers
2. Which of the following is the correct way to declare a nested DTO class inside a parent DTO in Spring Boot?
easy
A. public class ParentDTO { private class ChildDTO { private String name; } }
B. public class ParentDTO { class ChildDTO { private String name; } }
C. public class ParentDTO { public static class ChildDTO { private String name; } }
D. public class ParentDTO { static class ChildDTO { public String name; } }

Solution

  1. Step 1: Check nested class modifiers

    Static nested classes are recommended for DTOs to avoid implicit reference to outer class.
  2. Step 2: Validate access modifiers

    Public static nested class with private fields and getters/setters is standard practice.
  3. Final Answer:

    public class ParentDTO { public static class ChildDTO { private String name; } } -> Option C
  4. Quick Check:

    Static nested class with public modifier = public class ParentDTO { public static class ChildDTO { private String name; } } [OK]
Hint: Use public static nested class for nested DTOs [OK]
Common Mistakes:
  • Using non-static nested classes causing memory leaks
  • Declaring nested class as private making it inaccessible
  • Using public fields instead of private with getters/setters
3. Given the following nested DTO classes, what will be the output of System.out.println(order.getCustomer().getName()); if order is initialized as below?
public class OrderDTO {
  private CustomerDTO customer;
  public CustomerDTO getCustomer() { return customer; }
  public void setCustomer(CustomerDTO customer) { this.customer = customer; }
  public static class CustomerDTO {
    private String name;
    public String getName() { return name; }
    public void setName(String name) { this.name = name; }
  }
}

OrderDTO order = new OrderDTO();
OrderDTO.CustomerDTO cust = new OrderDTO.CustomerDTO();
cust.setName("Alice");
order.setCustomer(cust);
medium
A. Alice
B. null
C. Compilation error
D. Runtime NullPointerException

Solution

  1. Step 1: Analyze object initialization

    The customer object is created and its name is set to "Alice" before being assigned to order.
  2. Step 2: Check method calls

    Calling order.getCustomer().getName() returns the name "Alice" as set previously.
  3. Final Answer:

    Alice -> Option A
  4. Quick Check:

    Nested DTO getter returns set value = Alice [OK]
Hint: Set nested DTO fields before accessing getters [OK]
Common Mistakes:
  • Forgetting to set nested DTO before calling getter
  • Confusing null with empty string
  • Assuming compilation error due to nested class
4. Identify the error in the following nested DTO code snippet:
public class UserDTO {
  private AddressDTO address;
  public static class AddressDTO {
    private String city;
    public String getCity() { return city; }
    public void setCity(String city) { this.city = city; }
  }

  public AddressDTO getAddress() { return address; }
  public void setAddress(AddressDTO address) { this.address = address; }
}

UserDTO user = new UserDTO();
user.getAddress().setCity("Paris");
medium
A. Compilation error due to missing constructor
B. No error, code runs correctly
C. IllegalAccessError on accessing city field
D. NullPointerException because address is not initialized

Solution

  1. Step 1: Check object initialization

    The address field in UserDTO is never initialized, so it is null by default.
  2. Step 2: Analyze method call

    Calling user.getAddress().setCity("Paris") tries to call setCity on null, causing NullPointerException.
  3. Final Answer:

    NullPointerException because address is not initialized -> Option D
  4. Quick Check:

    Uninitialized nested DTO causes NullPointerException [OK]
Hint: Always initialize nested DTO before calling its methods [OK]
Common Mistakes:
  • Assuming default constructor initializes nested DTO
  • Thinking compilation error occurs
  • Ignoring possibility of NullPointerException
5. You have a nested DTO structure where OrderDTO contains a list of ItemDTO objects. You want to convert this nested DTO into a flat list of item names using Java streams. Which code snippet correctly achieves this?
public class OrderDTO {
  private List<ItemDTO> items;
  public List<ItemDTO> getItems() { return items; }
  public void setItems(List<ItemDTO> items) { this.items = items; }
  public static class ItemDTO {
    private String name;
    public String getName() { return name; }
    public void setName(String name) { this.name = name; }
  }
}

OrderDTO order = ...; // initialized with items
hard
A. List<String> names = order.getItems().stream().map(OrderDTO.ItemDTO::getName).toList();
B. List<String> names = order.getItems().stream().flatMap(ItemDTO::getName).collect(Collectors.toList());
C. List<String> names = order.getItems().map(ItemDTO::getName).collect(Collectors.toList());
D. List<String> names = order.getItems().stream().map(item -> item.name).collect(Collectors.toList());

Solution

  1. Step 1: Understand stream mapping

    To get a list of names, map each ItemDTO to its name using map(OrderDTO.ItemDTO::getName).
  2. Step 2: Collect results

    Use toList() (Java 16+) or collect(Collectors.toList()) to gather results into a list.
  3. Final Answer:

    List<String> names = order.getItems().stream().map(OrderDTO.ItemDTO::getName).toList(); -> Option A
  4. Quick Check:

    Stream map + toList() = List<String> names = order.getItems().stream().map(OrderDTO.ItemDTO::getName).toList(); [OK]
Hint: Use stream().map(...).toList() to extract nested DTO fields [OK]
Common Mistakes:
  • Using flatMap instead of map for simple field extraction
  • Calling map on List directly without stream()
  • Accessing private fields without getter