[英]Mapstruct self defined mapper AND automatically generated one
I understand Mapstruct
allows me to define my own mapper logic, I am doing it like this: 我理解
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;
}
}
It works just fine, but I also want Mapstruct
's generated mappers, but they have to be defined in an interface, is there a way to group up both of these mapper types? 它工作正常,但我也想要
Mapstruct
的生成映射器,但它们必须在接口中定义,有没有办法对这两种映射器类型进行分组?
NOTE: Untested. 注意:未经测试。 I used the following solution once in a Spring-Boot project using MapStruct version 1.0.0.Final.
我在使用MapStruct版本1.0.0.Final的Spring-Boot项目中使用了以下解决方案一次。
Customizing standard mapping process is fairly well documented . 定制标准映射过程已得到很好的记录 。
One of the way to customize your mappings are 'AfterMapping' and 'BeforeMapping' hooks : 自定义映射的方法之一是'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());
}
}
}
Then annotate the standard mapper interface with uses
and exclude the custom mapped fields from the standard mapping: 然后注释与标准映射器接口
uses
和排除标准映射自定义映射的字段:
@Mapper(componentModel = "spring", uses = {ProjectMapperExtension.class})
public interface ProjectMapper {
@Mapping(target = "id", ignore = true)
@Mapping(target = "organisation", ignore = true)
ProjectInfo mapProjectEntityToProjectInfo(ProjectEntity projectEntity);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.