Springboot2.x 通过自定义 DTO 实现 接口响应数据隐藏

参考

  1. 【SpringREST实体(entity)与数据传输对象(DTO)间的转换-哔哩哔哩
  2. Spring Boot DTO示例:实体到DTO的转换

步骤

  1. pom.xml dependencies 中添加
        <dependency>
            <groupId>org.modelmapper</groupId>
            <artifactId>modelmapper</artifactId>
            <version>2.4.2</version>
        </dependency>
  1. 入口文件注册 @Bean
public class SuddenlyNlineLearningPlatformApplication {

//    装配bean 实现dto转换类自动注入
    @Bean
    public ModelMapper modelMapper() {
        return new ModelMapper();
    }

    public static void main(String[] args) {
        SpringApplication.run(SuddenlyNlineLearningPlatformApplication.class, args);
    }

}

  1. 根据实体创建对应接口相应的 DTO 类
    学生实体参考:
public class Student implements Serializable {
    /**
     * 序列化安全
     */
    private static final long serialVersionUID = 1L;

    private Integer id;
    /**
     * 账号
     */
    private String account;
    /**
     * 密码
     */
    private String password;
    /**
     * 用户名
     */
    private String name;
    /**
     * 头像
     */
    private String avatarUrl;
    /**
     * 性别
     */
    private Byte gender;
    /**
     * 手机号
     */
    private String phoneNumber;
    /**
     * 手机号验证状态
     */
    private byte phoneVerificationStatus;
    /**
     * 账号
     */
    private String bewrite;
    /**
     * 创建时间
     */
    private Date createdAt;
    /**
     * 更新时间
     */
    private Date updatedAt;
}

接口不想显示密码与实践字段,创建对应的DAO,DAO参考

public class InfoStudentDto implements Serializable {
    /**
     * 序列化安全
     */
    private static final long serialVersionUID = 1L;

    private Integer id;
    /**
     * 用户名
     */
    private String name;
    /**
     * 头像
     */
    private String avatarUrl;
    /**
     * 性别
     */
    private Byte gender;
    /**
     * 手机号
     */
    private String phoneNumber;
}

  1. 在控制器内使用
public class Info {
    @Autowired
    StudentService studentService;
    // 自动注入
    @Autowired
    ModelMapper modelMapper;

    /**
     * 根据id获取学生信息
     */
    @ApiOperation(value = "显示学生信息", notes = "查看别人的(隐藏部分字段)")
    @ApiImplicitParam(name = "id", value = "学生id", required = true,
            dataType = "int", paramType = "query")
    @RequestMapping(value = "show", method = RequestMethod.GET)
    public ResponseEntity<ResponseBody<InfoStudentDto>> show(@RequestParam("id") Integer id){
        // 转换
        InfoStudentDto infoStudentDto = modelMapper.map(studentService.findById(id), InfoStudentDto.class);
        return ResponseEntity.ok( new ResponseBody(infoStudentDto));
    }
}
  1. 运行测试

image

总结

  1. 没有演示如何转换list
  2. 没有测试DTO转实体
posted @ 2021-08-05 10:47  夏秋初  阅读(1124)  评论(0编辑  收藏  举报