Quantcast
Channel: Baeldung
Viewing all articles
Browse latest Browse all 3733

How to Map a Source Object to the Target List Using MapStruct?

$
0
0

1. Overview

In this tutorial, we’ll use the MapStruct library to populate a List in a target object from specific attributes of a source object. While MapStruct primarily relies on mapping annotations for object conversion, it also provides flexible options for custom transformations when annotations fall short.

We’ll start by discussing a simple use case where annotations alone cannot handle the conversion. Then, we’ll explore alternative approaches using MapStruct. Finally, we’ll validate our solution by running the implemented program.

2. Use Case

Before discussing the conversion use case, let’s discuss a few important classes:

 

Let’s start with the source Car class:

public class Car {
    private String make;
    private String model;
    private int year;
    private int seats;
    private String plant1;
    private String plant1Loc;
    private String plant2;
    private String plant2Loc;
    public Car(String make, String model, int year, int seats) {
        this.make = make;
        this.model = model;
        this.year = year;
        this.seats = seats;
    }
    
    //Standard Getter and Setter methods...
}

In addition to the usual attributes of a car, in the Car class we’ve four attributes for storing the manufacturing plants and their locations. Also, there’s a constructor that takes four arguments.

Next, let’s take a look at the target CarDto class:

public class CarDto {
    private String make;
    private String model;
    private int year;
    private int numberOfSeats;
    private List<ManufacturingPlantDto> manufacturingPlantDtos;
    public CarDto(String make, String model, int year, int numberOfSeats) {
        this.make = make;
        this.model = model;
        this.year = year;
        this.numberOfSeats = numberOfSeats;
    }
    
    //Standard Getter and Setter methods...
}

CarDto has the usual attributes, getter, and setter methods, and a constructor like the Car class. However, it has an additional List attribute containing elements of type ManufacturingPlantDto:

public class ManufacturingPlant {
    private String name;
    private String location;
    public ManufacturingPlant(String name, String location) {
        this.name = name;
        this.location = location;
    }
}

It has two string attributes, name and location. Additionally, a constructor accepts a couple of arguments to set the values of these two attributes.

Each CarDto object created from a Car object must have two ManufacturingPlantDto objects in the list attribute manufacturingPlantDtos. Car#plant1 and Car#plant2 map to ManufacturingPlantDto#name in each CarDto#manufacturingPlants list elements. Similarly, the Car#plant1Loc and Car#plant2Loc map to the ManufacturingPlantDto#location attribute in each CarDto#manufacturingPlantDtos elements list.

Next, we’ll discuss solving this use case using the MapStruct library.

3. Map Using Expressions

Usually, we use the target and source attributes in the @Mapping annotation to map the source object attributes to target object attributes. However, MapStruct provides additional flexibility to handle more complex mappings with the help of the expressions attribute. The expression attribute helps embed custom Java code to implement complex mapping logic. In addition, the Java code has access to the source object.

Let’s implement the CarMapper interface with the carToCarDto() mapper method:

@Mapper(imports = { Arrays.class, ManufacturingPlantDto.class })
public interface CarMapper {
    CarMapper INSTANCE = Mappers.getMapper(CarMapper.class);
    @Mapping(target = "numberOfSeats", source = "seats")
    @Mapping(
        target = "manufacturingPlantDtos",
        expression = """
          java(Arrays.asList(
          new ManufacturingPlantDto(car.getPlant1(), car.getPlant1Loc()),
          new ManufacturingPlantDto(car.getPlant2(), car.getPlant2Loc())
            ))
        """
    )
    CarDto carToCarDto(Car car);
}

This is a basic mapper annotated with the @Mapper annotation at the interface level and @Mapping annotation at the method level. The @Mapper annotation has the imports attribute, helping to import the Array and the ManufacturingPlantDto class. In the interface, we must import the classes used in the Java code embedded in the expression attribute of the @Mapping annotation over the carToCarDto() method.

Further, the Java code uses Arrays#asList() method to create a List object with two elements of type ManufacturingPlantDto class. Further, the expression extracts the manufacturing plant and its location from the source Car object to pass them as arguments into the ManufacturingPlantDto‘s constructor. Moreover, we can handle more complex scenarios by invoking other custom methods from the expression. For that, we must import the relevant classes in the @Mapper annotation.

After compilation, the generated CarMapperImpl class uses the expression code to implement the custom mapping.

Now, let’s see if the generated implementation of CarMapper interface creates CarDto from Car object:

void whenUseMappingExpression_thenConvertCarToCarDto() {
    Car car = createCarObject();
    CarDto carDto = CarMapper.INSTANCE.carToCarDto(car);
    assertEquals("Morris", carDto.getMake());
    assertEquals("Mini", carDto.getModel());
    assertEquals(1969, carDto.getYear());
    assertEquals(4, carDto.getNumberOfSeats());
    validateTargetList(carDto.getManufacturingPlantDtos());
}

In the beginning of the program, the createCarObject() method creates a test instance of the Car class:

Car createCarObject() {
    Car car = new Car("Morris", "Mini", 1969, 4);
    car.setPlant1("Oxford");
    car.setPlant1Loc("United Kingdom");
    car.setPlant2("Swinden");
    car.setPlant2Loc("United Kingdom");
    return car;
}

Then, we pass on this Car instance as an argument to the CarMapper#carToCarDto() method. Finally, when we run this program, the resulting CarDto object is created exactly as expected with two ManufacturingPlantDto elements in the CarDto#manufacturingPlantDtos List attribute.

4. Map Using Decorators

The MapStruct library’s decorators feature also helps write custom logic to map Java bean properties. We’ll learn more about it.

Let’s consider a mapper class for converting the Car object to CarDto object:

@Mapper
@DecoratedWith(CarMapperDecorator.class)
public interface CustomCarMapper {
    CustomCarMapper INSTANCE = Mappers.getMapper(CustomCarMapper.class);
    @Mapping(source = "seats", target = "numberOfSeats")
    CarDto carToCarDto(Car car);
}

In the CustomCarMapper interface, for straightforward mapping between Car#seats and CarDto#numberOfSeats properties @Mapping annotation is quite effective. However, we’ll use a decorator like CarMapperDecorator class to implement custom logic to map the Car properties to the elements of the CarDto#ManufacturingPlantDtos List property. We must configure the decorator using the @DecoratedWith annotation on the mapper interface.

Moving on, let’s take a look at the CarMapperDecorator class:

public abstract class CarMapperDecorator implements CustomCarMapper {
    private final Logger logger = LoggerFactory.getLogger(CarMapperDecorator.class);
    private CustomCarMapper delegate;
    public CarMapperDecorator(CustomCarMapper delegate) {
        this.delegate = delegate;
    }
    @Override
    public CarDto carToCarDto(Car car) {
        CarDto carDto = delegate.carToCarDto(car);
        carDto.setManufacturingPlantDtos(getManufacturingPlantDtos(car));
        return carDto;
    }
    private List getManufacturingPlantDtos(Car car) {
    // some custom logic or transformation which may require calls to other services
        return Arrays.asList(
          new ManufacturingPlantDto(car.getPlant1(), car.getPlant1Loc()),
          new ManufacturingPlantDto(car.getPlant2(), car.getPlant2Loc())
       );
    }
}

The CarMapperDecorator class is an abstract implementation of the CustomCarMapper interface. It overrides the CustomCarMapper#carToCarDto() method, invoking the getManufacturingPlantDtos() method after performing the standard mapping via the @Mapping annotation. The method getManufacturingPlantDtos(), essentially handles the conversion logic.

The concrete mapper implementation generated after compilation handles the mapping during the runtime.

Moving on, let’s run the program:

void whenUsingDecorator_thenConvertCarToCarDto() {
    Car car = createCarObject();
    CarDto carDto = CustomCarMapper.INSTANCE.carToCarDto(car);
    assertEquals("Morris", carDto.getMake());
    assertEquals("Mini", carDto.getModel());
    assertEquals(1969, carDto.getYear());
    assertEquals(4, carDto.getNumberOfSeats());
    validateTargetList(carDto.getManufacturingPlantDtos());
}

The program successfully maps the Car properties to the CarDto properties. Moreover, the CarMapperDecorator class handles the custom logic to create the CarDto#manufacturingPlantDtos List property.

5. Map Using Qualifiers

We can use the @Mapping annotation’s qualifiedByName attribute to specify custom mapper methods. For example, to derive the CarDto#manufacturingPlantDtos property from the Car object, we can point to the method mapPlants():

@Mapper
public interface QualifiedByNameCarMapper {
    QualifiedByNameMapper INSTANCE = Mappers.getMapper(QualifiedByNameMapper.class);
    @Mapping(source = "seats", target = "numberOfSeats")
    @Mapping(target = "manufacturingPlantDtos", source = "car", qualifiedByName = "mapPlants")
    CarDto carToCarDto(Car car);
    @Named("mapPlants")
    default List<ManufacturingPlantDto> mapPlants(Car car) {
        return List.of(
          new ManufacturingPlantDto(car.getPlant1(), car.getPlant1Loc()),
          new ManufacturingPlantDto(car.getPlant2(), car.getPlant2Loc())
        );
    }
}

In the QualifiedByNameCarMapper interface, the mapPlants() method implements the mapping logic for the specific target CarDto#manufacturingPlantDtos property.

Further after compilation, the QualifiedByNameCarMapper’s implementor class is generated. Finally, when we run the program, the CarDto#manufacturingPlants property gets created correctly from the Car object properties:

void whenUsingQualifiedByName_thenConvertCarToCarDto() {
    Car car = createCarObject();
    CarDto carDto = QualifiedByNameCarMapper.INSTANCE.carToCarDto(car);
    assertEquals("Morris", carDto.getMake());
    assertEquals("Mini", carDto.getModel());
    assertEquals(1969, carDto.getYear());
    assertEquals(4, carDto.getNumberOfSeats());
validateTargetList(carDto.getManufacturingPlantDtos());
}

6. Conclusion

In this article, we discussed the various ways to use the properties of a source object to create the elements of a list attribute in a target object.

The @Mapping annotation with the help of source and target attributes can handle straightforward mappings. Luckily, the library also offers flexibility with the help of expressions, decorators, and qualifiers to apply complex conversion logic. As a result, they contribute immensely to enhancing its usability and further adoption in application development.

As usual, the code used in this article is available over on GitHub.

The post How to Map a Source Object to the Target List Using MapStruct? first appeared on Baeldung.
       

Viewing all articles
Browse latest Browse all 3733

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>