1

我理解Mapstruct允许我定义自己的映射器逻辑,我这样做是这样的:

@Mapper(componentModel = "spring")
public abstract class ProjectMapper {

    public ProjectInfo map(ProjectEntity projectEntity) {
        ProjectInfo projectInfo = new ProjectInfo();
        projectInfo.setName(projectEntity.getName());
        projectInfo.setDescription(projectEntity.getDescription());

        // Specific logic that forces me to define it myself
        if (projectEntity.getId() != null) {
            projectInfo.setId(projectEntity.getId());
        }
        if (projectEntity.getOrganisation() != null) {
            projectInfo.setOrganisation(projectEntity.getOrganisation().getName());
        }
        return projectInfo;
    }
}

它工作得很好,但我也想要Mapstruct生成的映射器,但它们必须在接口中定义,有没有办法对这两种映射器类型进行分组?

4

1 回答 1

0

注意:未经测试。我在使用 MapStruct 版本 1.0.0.Final 的 Spring-Boot 项目中使用了以下解决方案。

定制标准映射过程有很好的文档记录

自定义映射的一种方法是“AfterMapping”和“BeforeMapping”钩子

@Mapper
public abstract class ProjectMapperExtension {

    @AfterMapping
    public void mapProjectEntityToProjectInfo(ProjectEntity projectEntity, @MappingTarget ProjectInfo projectInfo) {

        if (projectEntity.getId() != null) {
            projectInfo.setId(projectEntity.getId());
        }

        if (projectEntity.getOrganisation() != null) {
            projectInfo.setOrganisation(projectEntity.getOrganisation().getName());
        }
    }
}

然后用标准映射注释标准映射器接口uses并从标准映射中排除自定义映射字段:

@Mapper(componentModel = "spring", uses = {ProjectMapperExtension.class})
public interface ProjectMapper {

    @Mapping(target = "id", ignore = true)
    @Mapping(target = "organisation", ignore = true)
    ProjectInfo mapProjectEntityToProjectInfo(ProjectEntity projectEntity);
}
于 2017-06-08T12:04:12.597 回答