前言
我们在使用Springboot JPA查询数据内容时,大多数是直接返回表对应的实体类,但是有时候我们需要增加或减少实体类的字段。
即创建一个自定义返回类VO,使用JPA查询,repository接口中直接返回VO
一、使用场景
- 关联查询时使用,两个表中的字段同时在一个类中展示
- 返回一部分字段,返回值不需要或者不能返回全部字段,如实体类中包含密码,则不能展示密码字段
二、解决方法
- 创建构造方法。
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;
}
}
- 编写@Query查询语句
- nativeQuery = false或者省略nativeQuery
- select 后接 new DeviceJobStatusVO(……)
- 注意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);
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
文章由极客之音整理,本文链接:https://www.bmabk.com/index.php/post/71736.html