一佑力、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);
}
}