• springboot jpa 返回自定义非实体VO类



    前言

    我们在使用Springboot JPA查询数据内容时,大多数是直接返回表对应的实体类,但是有时候我们需要增加或减少实体类的字段。
    即创建一个自定义返回类VO,使用JPA查询,repository接口中直接返回VO


    一、使用场景

    1. 关联查询时使用,两个表中的字段同时在一个类中展示
    2. 返回一部分字段,返回值不需要或者不能返回全部字段,如实体类中包含密码,则不能展示密码字段

    二、解决方法

    1. 创建构造方法。
      DeviceJobStatusVO类中创建对应的构造方法:
     public class DeviceJobStatusVO {
    
        private String deviceId;
    
        private String deviceName;
    
        private String jobId;
    
        private String deviceVersion;
    
        @JsonFormat(pattern = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'", timezone = "GMT")
        private Date updatedTime;
    
        private Integer status;
    
        private String statusDescription;
    
        public DeviceJobStatusVO(String deviceId, String deviceName, String jobId, String deviceVersion, Date updatedTime, Integer status, String statusDescription) {
            this.deviceId = deviceId;
            this.deviceName = deviceName;
            this.jobId = jobId;
            this.deviceVersion = deviceVersion;
            this.updatedTime = updatedTime;
            this.status = status;
            this.statusDescription = statusDescription;
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    1. 编写@Query查询语句
      1. nativeQuery = false或者省略nativeQuery
      2. select 后接 new DeviceJobStatusVO(……)
      3. 注意new 的类名前面要写全部具体的路径!!!!!!!!!!
    @Query(value = "select new com.inspur.iot.resource.VO.DeviceJobStatusVO (d.deviceId, t.name, d.resourceJobId, d.deviceVersion,d.updatedTime,d.status,d.statusDescription) from Device t inner join ResourceJobStatus d on t.id=d.deviceId where d.resourceJobId=:jobId and t.name like %:queryData% order by d.updatedTime desc, t.id desc")
    Page<DeviceJobStatusVO> listDeviceJobByJobIdQuery(@Param("jobId") String jobId, @Param("queryData") String queryData, Pageable pageable);
    
    • 1
    • 2

  • 相关阅读:
    ThreadLocal&上传下载文件
    Linux安装Jenkins详细步骤
    dubbo 用户指南
    聊聊druid的borrow行为
    浅述在线播放URL机制
    CoordinatorLayout/AppBarLayout记录滚动位置异常问题
    springboot
    强强联合:OpenFeign 整合 Sentinel
    windows 查看端口被占用
    2022-01-22-JDBC
  • 原文地址:https://blog.csdn.net/qq_39231899/article/details/127439812