1.导入依赖
<dependency>
<groupId>org.mapstruct</groupId>
<artifactId>mapstruct</artifactId>
<version>1.4.2.Final</version>
</dependency>
<dependency>
<groupId>org.mapstruct</groupId>
<artifactId>mapstruct-processor</artifactId>
<version>1.4.2.Final</version>
</dependency>
2.编写转换类
@Mapper
public interface FollowUpDtoMapper {
FollowUpDtoMapper INSTANCES = Mappers.getMapper(FollowUpDtoMapper.class);
/**
* dto 转 vo
* @param dto dto
* @return vo
*/
FollowUpVO dtoToVo(FollowUpDTO dto);
}
这里关键的就是@Mapper这个注解,当我们写好之后,就会将我们的dto转为vo。当我们项目在编译阶段,就会自动帮我们生成实现类。
@Generated(
value = "org.mapstruct.ap.MappingProcessor",
date = "2022-01-25T15:50:13+0800",
comments = "version: 1.4.2.Final, compiler: javac, environment: Java 11.0.2 (Oracle Corporation)"
)
public class FollowUpDtoMapperImpl implements FollowUpDtoMapper {
@Override
public FollowUpVO dtoToVo(FollowUpDTO dto) {
if ( dto == null ) {
return null;
}
FollowUpVO followUpVO = new FollowUpVO();
followUpVO.setId( dto.getId() );
followUpVO.setFollowUpTime( dto.getFollowUpTime() );
followUpVO.setFollowUpInformation( dto.getFollowUpInformation() );
return followUpVO;
}
}
3.使用方法
FollowUpVO vo = FollowUpDtoMapper.INSTANCE.dtoToVo(dto);
4.特殊用法@Mapping
@Mapper
public interface FollowUpDtoMapper {
FollowUpDtoMapper INSTANCES = Mappers.getMapper(FollowUpDtoMapper.class);
/**
* dto 转 vo
* @param dto dto
* @return vo
*/
//这里代表dto转vo时,忽略vo中的column字段
@Mapping(target = "column", ignore = true)
//将dto中的name字段的值赋给vo中的productName字段
@Mapping(source = "name", target = "productName")
//BigDecimal转换成字符串
@Mapping(target = "blance", numberFormat = "#.00元")
//字符串转换成int
@Mapping(target = "age", numberFormat = "#岁")
FollowUpVO dtoToVo(FollowUpDTO dto);
//多数据源映射
//这里代表将dto1中的productName属性的值赋给vo的name字段,将dto2中的productDesc属性的值赋给vo的desc字段
@Mapping(source = "name", target = "dto1.productName")
@Mapping(source = "desc", target = "dto2.productDesc")
FollowUpVO dtoToVo(FollowUpDTO1 dto1, FollowUpDTO2 dto2);
}
特殊用法这些基本够用了,就不举例了。
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
文章由极客之音整理,本文链接:https://www.bmabk.com/index.php/post/67261.html