复制对象时,遇到属性名、类型不同。推荐使用mapstruct

复制对象时,遇到属性名、类型不同。推荐使用mapstruct,第1张

如何使用mapstruct解决复制时属性名、类型不同的问题
  • 1.引入pom包
  • 2.新建一个接口
  • 3.如何调用

1.引入pom包
        <dependency>
            <groupId>org.mapstruct</groupId>
            <artifactId>mapstruct</artifactId>
            <version>1.4.1.Final</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/org.mapstruct/mapstruct-processor -->
        <dependency>
            <groupId>org.mapstruct</groupId>
            <artifactId>mapstruct-processor</artifactId>
            <version>1.4.1.Final</version>
        </dependency>
       

** 因为当在maven install时候会出现属性找不到错误。没有对生成的bean进行setter

2.新建一个接口
import org.mapstruct.Mapper;
import org.mapstruct.Mapping;
import org.mapstruct.ReportingPolicy;
import org.mapstruct.factory.Mappers;

@Mapper(unmappedTargetPolicy = ReportingPolicy.WARN)
public interface BeanCopyUtil {
    BeanCopyUtil INSTANCE = Mappers.getMapper(BeanCopyUtil.class);

    @Mapping(target = "workcode", source = "workCode")
    @Mapping(target = "planId", source = "groupid")
    @Mapping(target = "planType", source = "kqtype")
    @Mapping(target = "onCheckTime", source = "workbegintime")
    @Mapping(target = "offCheckTime", source = "workendtime")
    @Mapping(target = "restBeginTime", source = "sleepBeginTime")
    @Mapping(target = "restEndTime", source = "sleepEndTime")
    //AttendanceSheduleEntity是目标对象。GetAllShiftsResponse是源对象
    AttendanceSheduleEntity allShiftsToAttendanceShedule(GetAllShiftsResponse getAllShiftsResponse);

}
       

注意mapper的引用包

3.如何调用
GetAllShiftsResponse x = new GetAllShiftsResponse();
AttendanceSheduleEntity attendanceSheduleEntity = BeanCopyUtil.INSTANCE.allShiftsToAttendanceShedule(x);
       

注意BeanCopyUtil.INSTANCE

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/langs/883698.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-14
下一篇 2022-05-14

发表评论

登录后才能评论

评论列表(0条)

保存