• 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

  • 相关阅读:
    Python3入门教程||Python3 XML解析
    微信也能控制PLC,仪器仪表了,想不到实现起来这么简单,GRM530
    【安卓基础6】数据存储
    【总结】两个独立同分布的随机变量相加还是原来的分布吗?
    What are the advantages of pipes over temporary files?
    伺服电机和步进电机的区别
    Hugging “Hugging Face“
    LED显示屏出现马赛克有哪些原因
    【MySQL精通之路】MySQL的使用(9)-设置环境变量
    MYSQL之增删改查(中)
  • 原文地址:https://blog.csdn.net/qq_39231899/article/details/127439812