我明白 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
生成的映射器,但它们必须在接口(interface)中定义,有没有办法将这两种映射器类型分组?
最佳答案
注意:未经测试。我在使用 MapStruct 版本 1.0.0.Final 的 Spring-Boot 项目中使用过以下解决方案。
自定义标准映射流程是fairly well documented .
自定义映射的方法之一是 'AfterMapping' and 'BeforeMapping' hooks :
@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
注释标准映射器接口(interface),并从标准映射中排除自定义映射字段:
@Mapper(componentModel = "spring", uses = {ProjectMapperExtension.class})
public interface ProjectMapper {
@Mapping(target = "id", ignore = true)
@Mapping(target = "organisation", ignore = true)
ProjectInfo mapProjectEntityToProjectInfo(ProjectEntity projectEntity);
}
关于java - Mapstruct 自定义映射器并自动生成一个,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44431750/