Advanced MapStruct for automated DTO to Entity mapping and vice-versa

Start this tutorial about MapStruct with the introduction.
MapStruct tries to map the field from one object to another automatically but when the objects are different you can map the object’s fields explicitly.

Animal class
public class Animal {
    private Breed breed;
    private Owner owner;
    //getters & setters
Breed class
public class Breed {
    private String name;
    private String country;
    private Integer height;
    //getters & setters
Owner class
public class Owner {
    private String name;
    private String address;
    //getters & setters
AnimalDTO class
public class AnimalDTO {
    private String xName;
    private String zName;
    //getters & setters
AnimalAnimalDTOMapper Interface
public interface AnimalAnimalDTOMapper {
    AnimalAnimalDTOMapper INSTANCE = Mappers.getMapper(AnimalAnimalDTOMapper.class);

            @Mapping(source = "", target = "xName"),
            @Mapping(source = "", target = "zName")}
    AnimalDTO objToDto(Animal animal);

    Animal dtoToObj(AnimalDTO animalDTO);
Controller – Mapper in action
@GetMapping(value = "/mapstruct_adv_obj_to_dto.action")
public AnimalDTO mapstructAdvObjToDto() {
    Animal animal = new Animal(
            new Breed("Boxer", "Germany", 120),
            new Owner("Gabriel Voicu", "Krakovia 10A")
    AnimalDTO animalDTO = AnimalAnimalDTOMapper.INSTANCE.objToDto(animal);
    return animalDTO;

Leave a Comment

Your email address will not be published. Required fields are marked *