ZeeSpire Software Solutions

Advanced MapStruct for automated DTO to Entity mapping and vice versa

Written by: Gabriel Voicu

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

The Mapper

AnimalAnimalDTOMapper Interface

public interface AnimalAnimalDTOMapper {
    AnimalAnimalDTOMapper INSTANCE = Mappers.getMapper(AnimalAnimalDTOMapper.class);

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

    Animal dtoToObj(AnimalDTO animalDTO);

And the action begins

@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;