Adds after / before mapping example (#7518)

This commit is contained in:
Nivedan Bamal
2019-08-08 01:38:03 -04:00
committed by Grzegorz Piwowarek
parent 69fb214962
commit 7f7fd337a7
6 changed files with 88 additions and 0 deletions

View File

@@ -8,4 +8,5 @@ import lombok.Setter;
public class CarDTO {
private int id;
private String name;
private FuelType fuelType;
}

View File

@@ -0,0 +1,5 @@
package com.baeldung.dto;
public enum FuelType {
ELECTRIC, BIO_DIESEL
}

View File

@@ -0,0 +1,4 @@
package com.baeldung.entity;
public class BioDieselCar extends Car {
}

View File

@@ -0,0 +1,4 @@
package com.baeldung.entity;
public class ElectricCar extends Car {
}

View File

@@ -0,0 +1,32 @@
package com.baeldung.mapper;
import org.mapstruct.AfterMapping;
import org.mapstruct.BeforeMapping;
import org.mapstruct.Mapper;
import org.mapstruct.MappingTarget;
import com.baeldung.dto.CarDTO;
import com.baeldung.dto.FuelType;
import com.baeldung.entity.BioDieselCar;
import com.baeldung.entity.Car;
import com.baeldung.entity.ElectricCar;
@Mapper
public abstract class CarsMapper {
@BeforeMapping
protected void enrichDTOWithFuelType(Car car, @MappingTarget CarDTO carDto) {
if (car instanceof ElectricCar)
carDto.setFuelType(FuelType.ELECTRIC);
if (car instanceof BioDieselCar)
carDto.setFuelType(FuelType.BIO_DIESEL);
}
@AfterMapping
protected void convertNameToUpperCase(@MappingTarget CarDTO carDto) {
carDto.setName(carDto.getName().toUpperCase());
}
public abstract CarDTO toCarDto(Car car);
}