1.引入mapstruct
<dependency>
<groupId>org.mapstruct</groupId>
<artifactId>mapstruct</artifactId>
</dependency>
<dependency>
<groupId>org.mapstruct</groupId>
<artifactId>mapstruct-processor</artifactId>
<scope>compile</scope>
</dependency>
2.定义接口
import com.jdl.jscaffold.dao.entity.*;
import org.mapstruct.Builder;
import org.mapstruct.InheritInverseConfiguration;
import org.mapstruct.Mapper;
import org.mapstruct.Mapping;
import org.mapstruct.factory.Mappers;
@Mapper(componentModel = "spring",
builder = @Builder(disableBuilder = true))
public interface EntityDtoMapper {
EntityDtoMapper instance = Mappers.getMapper(EntityDtoMapper.class);
@Mapping(source = "id", target = "id")
@Mapping(source = "createTime", target = "createTime")
@Mapping(source = "updateTime", target = "updateTime")
@Mapping(source = "createUser", target = "createUser")
@Mapping(source = "updateUser", target = "updateUser")
@Mapping(source = "yn", target = "yn")
@Mapping(source = "version", target = "version")
@Mapping(source = "jobTypeCode", target = "jobTypeCode")
@Mapping(source = "jobTypeName", target = "jobTypeName")
@Mapping(source = "jobTypeDesc", target = "jobTypeDesc")
@Mapping(target = "jobParams", ignore = true)
@Mapping(target = "tasks", ignore = true)
@Mapping(source = "templateId", target = "templateId")
JobDefineDto toJobDefineDto(JobDefine entity);
}
定义一个方法用于将JobDefine 对象转换为JobDefineDto 对象,并使用@Mapping注解指定映射字段
说明:
componentModel = "spring"
这个属性指定了生成的映射器应作为 Spring Bean 管理。这样,你可以在 Spring 应用程序中通过依赖注入来使用这个映射器。
componentModel = "spring":生成的映射器将被 Spring 容器管理。
其他可选值还包括 default(无特定组件模型)、cdi(Contexts and Dependency Injection)、jsr330(JSR-330 @javax.inject 注解)。
builder = @Builder(disableBuilder = true)
这个属性配置了 MapStruct 如何处理构建器(builder)模式。
disableBuilder = true:禁用构建器模式。如果你的目标对象有一个构建器(builder),但你不希望 MapStruct 使用它进行映射,你可以禁用它。
disableBuilder = false(默认值):启用构建器模式。如果目标对象有一个构建器,MapStruct 将使用它来创建目标对象。
3.使用
JobDefineDto xxxDto = EntityDtoMapper.instance.toJobDefineDto(jdEntity);
标签:dto,target,mapstruct,Mapping,source,import,entiy,org
From: https://www.cnblogs.com/PythonOrg/p/18242106