- 引入依赖
<dependencies> <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> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <version>1.18.20</version> </dependency> <!-- javax.annotation.Generated 类找不到错误--> <dependency> <groupId>javax.annotation</groupId> <artifactId>javax.annotation-api</artifactId> <version>1.3.2</version> </dependency> </dependencies>
- 添加plugin
<plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <version>3.8.1</version> <configuration> <source>1.8</source> <target>1.8</target> <annotationProcessorPaths> <path> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <version>1.18.20</version> </path> <path> <groupId>org.mapstruct</groupId> <artifactId>mapstruct-processor</artifactId> <version>1.4.2.Final</version> </path> </annotationProcessorPaths> </configuration> </plugin>
- 编写do与bo实体
// do 实体 @Data // 新增 @Accessors(chain = true) public class UserDO { // 用户编号 private Integer id; // 用户名 private String username; // 密码 private String password; // 时间戳形式的创建日期 private LocalDateTime createTime; } // bo 实体 @Data // 新增 @Accessors(chain = true) public class UserBO { // 用户编号 private Integer id; // 用户名 private String username; // 密码 private String password; // 日期形式的创建日期 private LocalDate createTime; }
- 编写convertor转换类
@Mapper( //null值忽略 nullValuePropertyMappingStrategy = NullValuePropertyMappingStrategy.IGNORE, //检查空值 nullValueCheckStrategy = NullValueCheckStrategy.ALWAYS, //没有mapping上的字段忽略 unmappedTargetPolicy = ReportingPolicy.IGNORE ) public interface UserConvert { UserConvert INSTANCE = Mappers.getMapper(UserConvert.class); // <2> @Mapping(source = "username", target = "username") @Mapping(source = "password", target = "password") @Mapping(target = "createTime", expression = "java(toLocalDate(userDO.getCreateTime()))") UserBO convert(UserDO userDO); /** * 时间戳转日期 * @param localDateTime 入参时间戳 * @return 日期 */ default LocalDate toLocalDate(LocalDateTime localDateTime){ if (localDateTime == null){ return null ; } return localDateTime.toLocalDate() ; } }
- 单元测试
@Slf4j public class UserBOTest { @Test public void hello() { // 创建 UserDO 对象 UserDO userDO = new UserDO() .setId(1) .setUsername("yudaoyuanma") .setPassword("buzhidao"); // <X> 进行转换 UserBO userBO = UserConvert.INSTANCE.convert(userDO); System.out.println(userBO.getId()); System.out.println(userBO.getUsername()); System.out.println(userBO.getPassword()); System.out.println(userBO.getCreateTime()); } }
- 文档:https://mapstruct.org/documentation/stable/reference/html
MapStruct学习笔记
于 2022-03-08 13:37:12 首次发布