16、SpringBoot------整合MapStruct
2024-08-23 16:09:34
开发工具:STS
前言:
前端提交往后端的数据,一部分是不需要存入数据库当中的;
后端从数据库中取出的数据,一部分是不可以交给用户的;
那么,po面向的是DB,vo面向的是客户端,
mapstruct就提供了vo与po自动转换的一种方式。
实例:
1.导入依赖:
<!-- https://mvnrepository.com/artifact/org.mapstruct/mapstruct-jdk8 -->
<dependency>
<groupId>org.mapstruct</groupId>
<artifactId>mapstruct-jdk8</artifactId>
<version>1.0.0.Final</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.mapstruct/mapstruct-processor -->
<dependency>
<groupId>org.mapstruct</groupId>
<artifactId>mapstruct-processor</artifactId>
<version>1.0.0.Final</version>
</dependency>
2.添加po
package com.xm.timeHotel.pojo; import lombok.Data; @Data
public class User { private String username;
private String password;
private String iconUrl; }
3.添加vo
package com.xm.timeHotel.controller.dto; import lombok.Data; @Data
public class UserDto { private String username;
private String iconUrl; }
4.添加mapper接口
package com.xm.timeHotel.controller.dto; import org.mapstruct.Mapper;
import org.mapstruct.factory.Mappers; import com.xm.timeHotel.pojo.User; @Mapper(componentModel="spring")
public interface UserDtoMapper { public User dtoToUser(UserDto userDto) ;
public UserDto userToDto(User user); }
5.添加controller
package com.xm.timeHotel.controller; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController; import com.xm.timeHotel.controller.dto.UserDtoMapper;
import com.xm.timeHotel.controller.dto.UserDto;
import com.xm.timeHotel.pojo.User; @RestController("/user")
public class UserController { @Autowired
private UserDtoMapper userDtoMapper; @PostMapping("/userDto")
public void getUser(UserDto userDto) {
User user = userDtoMapper.dtoToUser(userDto);
System.out.println(user);
} @PostMapping("/user")
public void getUserDto(User user) {
UserDto userDto = userDtoMapper.userToDto(user);
System.out.println(user);
} }
6.eclipse生成不了mapper接口实现类的解决方案:
我直接运行项目的时候,发现一直未找到UserDtoMapper实例,从网上查找了好多种方案,都不能生效。
最后发现:
运行mvn clean项目,再mvn install项目,就生成实现类了。
最新文章
- Ajax工作流程
- 转 Netflix OSS、Spring Cloud还是Kubernetes? 都要吧!
- 简单C程序生成的汇编代码分析
- CUBRID学习笔记 48查询优化
- ProcExp和TaskMgr的列对比
- Fluent Nhibernate and Stored Procedures
- uva514(trail)(模拟栈)
- HOG参数简介及Hog特征维数的计算(转)
- java获取计算机硬件参数
- Oracle视图基础
- http://codeforces.com/contest/610/problem/D
- javascript预览图片——IT轮子系列(九)
- linux----------linux下安装rar和unrar命令
- nginx限制单个IP的最大连接数量限制下载速度
- /bin/sh^M:bad interpreter:
- Python 入门网络爬虫之精华版
- datacolumn 表达式 除数为0
- Results the mutual for the first time(alpha阶段总结)
- SpringMVC整合ActiveMQ
- Xilinx中解决高扇出的方法