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

MapStruct : mapping multiple source fields to one target field

考虑以下 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();
    }
}

有什么办法可以实现吗?

首先,我会为 Mappers 使用 public 摘要 class。更容易扩展它们并在生成的代码和抽象 class 之间创建继承。但这是您的解决方案: 您可以通过创建一个 @AfterMapping 注释方法来实现这一点。所以像

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

MapStruct documentation

这是我的答案。

@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(target = "fullName", source = ".", qualifiedByName="toFullName")

它可以通过参数使用源对象。