Проблема в том, что методы, отмеченные @AfterMapping
, вообще не вызываются.От testToEntityMapping
он переходит к toEntity
методу, но не вызывает ни один из toEntityAfterMapping()
методов.Зачем ?Является ли это возможным ?Как мне добиться этого с помощью MapStruct?
(Здесь я подготовил сценарий, который не имеет смысла, но полностью отражает суть моего вопроса)
Сущность:
public class Ford {
private String color;
private String market;
private int totalWidth;
//getters and setters omitted for brevity
}
Dtos:
public abstract class FordDto {
public String market;
public String color;
//getters and setters omitted for brevity
}
public class EuropeanFordDto extends FordDto{
private int totalWidth;
public int getTotalWidth() {
return totalWidth + 2;//"+2" for EU market
}
//setter omitted for brevity
}
public class AmericanFordDto extends FordDto{
private int totalWidth;
public int getTotalWidth() {
return totalWidth + 1;//"+1" for US market
}
//setter omitted for brevity
}
Mappers:
public abstract class FordMapper<D extends FordDto> {
public Ford toEntity(D dto) {
/* fill in fields common to both ford versions */
final Ford ford = new Ford();
ford.setColor(dto.getColor());
ford.setMarket(dto.getMarket());
return ford;
}
}
@Mapper(componentModel = "spring")
public abstract class EuropeanFordMapper extends FordMapper<EuropeanFordDto> {
@AfterMapping
public void toEntityAfterMapping(final EuropeanFordDto dto, @MappingTarget final Ford entity) {
/* Fill in fields related to european version of the ford */
entity.setTotalWidth(dto.getTotalWidth());
}
}
@Mapper(componentModel = "spring")
public abstract class AmericanFordMapper extends FordMapper<AmericanFordDto> {
@AfterMapping
public void toEntityAfterMapping(final AmericanFordDto dto, @MappingTarget final Ford entity) {
/* Fill in fields related to american version of the ford */
entity.setTotalWidth(dto.getTotalWidth());
}
}
Сервис:
@Service
public class CarService {
@Autowired
private AmericanFordMapper americanFordMapper;
@Autowired
private EuropeanFordMapper europeanFordMapper;
public void testToEntityMapping(final FordDto dto) {
if (dto instanceof AmericanFordDto) {
americanFordMapper.toEntity((AmericanFordDto) dto);
} else {
europeanFordMapper.toEntity((EuropeanFordDto) dto);
}
}
}