Prev Next

Java / MapStruct Java Interview questions

🔹 Basic Questions

  1. What is MapStruct?
    MapStruct is a Java annotation processor that generates type-safe, performant, and boilerplate-free mapping code between Java beans at compile time.
  2. How does MapStruct differ from other mapping frameworks like ModelMapper or Dozer?
    Performance, type safety, and no runtime dependency.
  3. What are the advantages of using MapStruct?
    Compile-time mapping, better performance, type-safety, easy customization.
  4. How do you define a mapper in MapStruct?
    @Mapper
    public interface CarMapper {
        CarMapper INSTANCE = Mappers.getMapper(CarMapper.class);
        CarDto carToCarDto(Car car);
    }
  5. What is the role of the @Mapper annotation?
    It marks an interface or abstract class as a MapStruct mapper, triggering code generation.

🔹 Intermediate Questions

  1. How do you map fields with different names?
    @Mapping(source = "carName", target = "name")
  2. How do you ignore a field in MapStruct?
    @Mapping(target = "someField", ignore = true)
  3. How do you map nested objects or collections?
    Define a mapper for the nested type or let MapStruct generate them automatically.
    @Mapping(source = "engine.type", target = "engineType")
  4. How to use @MappingTarget?
    void updateCarFromDto(CarDto dto, @MappingTarget Car car);
  5. What is the use of @InheritInverseConfiguration?
    Reverses the mapping logic from an existing method to avoid duplication.

🔹 Advanced Questions

  1. How to handle custom logic or transformations?
    @Mapping(target = "price", expression = "java(convertPrice(car.getPrice()))")
  2. What is @AfterMapping and @BeforeMapping?

    Hook methods to execute logic before or after mapping.

    @AfterMapping
    void enrichCar(@MappingTarget CarDto dto) {
        dto.setFullName(dto.getBrand() + " " + dto.getModel());
    }
  3. How do you map enums with MapStruct?
    By default, same-name enums are mapped automatically. Use @ValueMapping for custom behavior.
  4. How does MapStruct handle null values?
    @Mapper(nullValueMappingStrategy = NullValueMappingStrategy.RETURN_DEFAULT)
  5. Can you use dependency injection with MapStruct?
    @Mapper(componentModel = "spring")

🔹 Real-world / Scenario-Based

  1. In a large project, how do you organize your mappers?
    Group by domain/module, use composition, and define a central @MapperConfig.
  2. How do you handle circular dependencies?
    Avoid cycles in DTOs or use @Context and lifecycle methods carefully.
  3. How do you write unit tests for MapStruct mappers?
    Use JUnit to assert values from mapper method outputs.
  4. How do you map using other services?
    Inject services with @Context or use custom expressions/methods.
  5. How do you debug MapStruct-generated code?
    Inspect generated code under target/generated-sources/annotations.
«
»
Spring

Comments & Discussions