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. 编写@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);

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值