MapStruct:将多个源字段映射到一个目标字段

时间:2019-11-04 04:56:41

标签: mapstruct

请考虑以下POJO:

public class PersonVo {
    private String firstName;
    private String lastName;
}

private class PersonEntity {
    private String fullName;
}

我要使用MapStruct创建从PersonVoPersonEntity的映射器。
我需要将多个源字段firstNamelastName映射到一个目标字段fullName

这是我想要的伪代码。

[想要的解决方案A]

@Mapper
public interface PersonMapper {
    @Mapping(target = "fullName", source = {"firstName", "lastName"}, qualifiedByName="toFullName")
    PersonEntity toEntity(PersonVo person);

    @Named("toFullName")
    String translateToFullName(String firstName, String lastName) {
        return firstName + lastName;
    }
}

[解决方案B]

@Mapper
public interface PersonMapper {
    @Mapping(target = "fullName", source = PersonVo.class, qualifiedByName="toFullName")
    PersonEntity toEntity(PersonVo person);

    @Named("toFullName")
    String translateToFullName(PersonVo pserson) {
        return pserson.getFirstName() + pserson.getLastName();
    }
}

有什么办法可以实现?

2 个答案:

答案 0 :(得分:1)

这是我的答案。

@Mapper
public interface PersonMapper {
    @Mapping(target = "fullName", source = ".", qualifiedByName="toFullName")
    PersonEntity toEntity(PersonVo person);

    @Named("toFullName")
    String translateToFullName(PersonVo pserson) {
        return pserson.getFirstName() + pserson.getLastName();
    }
}

重点是

  

@Mapping(目标=“ fullName”, 源=“。” ,qualifiedByName =“ toFullName”)

可以按参数使用源对象。

答案 1 :(得分:0)

首先,我将使用Mappers的公共抽象类。使扩展它们并在生成的代码和抽象类之间创建继承变得更加容易。但是这是您的解决方案: 您可以通过创建@AfterMapping带注释的方法来实现。像

@AfterMapping
default void concat(@MappingTarget PersonEntity person, PersonVo person) {
  ... manipulate the target value
}

MapStruct documentation

相关问题