一、maven依赖
<dependency>
<groupId>org.mapstruct</groupId>
<artifactId>mapstruct-jdk8</artifactId>
<version>1.3.1.Final</version>
</dependency>
<dependency>
<groupId>org.mapstruct</groupId>
<artifactId>mapstruct-processor</artifactId>
<version>1.3.1.Final</version>
</dependency>
二、plugin插件
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>1.8</source>
<target>1.8</target>
<encoding>UTF-8</encoding>
<annotationProcessorPaths>
<path>
<groupId>org.mapstruct</groupId>
<artifactId>mapstruct-processor</artifactId>
<version>1.3.1.Final</version>
</path>
<path>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.12</version>
</path>
</annotationProcessorPaths>
</configuration>
</plugin>
注意:lombok插件必须同时配置,如果你使用了lombok插件的话
三、DTO以及DO定义
@Data
@AllArgsConstructor
@NoArgsConstructor
public class UserDO {
private Integer useId;
private String useName;
private String useSex;
private Integer useAge;
private String userMovie;
}
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class UserDto {
private String useName;
private String age;
private String movie;
}
四、mapper定义
@Mapper
public interface ModelConvertor {
ModelConvertor INSTANCE = Mappers.getMapper(ModelConvertor.class);
/**
* UserDO->userDTO
* @param user userDO模型
* @return userDTO实体对象
*/
@Mappings({
@Mapping(target = "age", source = "useAge"),
@Mapping(target = "movie", source = "userMovie")
})
UserDto toUser(UserDO user);
}
五、使用
@RestController
@RequestMapping("/user")
@Slf4j
public class UseController {
@PostMapping("/console")
public ResultDTO<UserDto> queryUser(@RequestBody UserDto userDto) {
return ResultDTO.success(userDto);
}
@PostMapping("/test")
public ResultDTO<UserDto> test(@RequestBody User user) {
UserDto userDto = ModelConvertor.INSTANCE.toUser(user);
return ResultDTO.success(userDto);
}
}
网友评论