springboot jpa中返回自定义对象

àì夳堔傛蜴生んèń 2021-05-20 14:19 764阅读 0赞

项目中使用springboot jpa进行持久层操作,大部分的操作不用手写sql。最近需要根据部门查询所有的用户,但是只需要用户id和用户userName两个字段,并不需要所有的字段。

一. 一般字段返回

1.首先需要自定义vo来接收字段,这里注意需要使用 @JsonProperty将属性与数据库字段对应上,并需要重写构造方法,不然会报错

  1. @Data
  2. public class UserDto {
  3. /**
  4. * 用户id
  5. */
  6. @JsonProperty("id")
  7. private Long userId;
  8. /**
  9. * 真实姓名
  10. */
  11. @JsonProperty("real_name")
  12. private String realName;
  13. public UserDto(Long userId, String realName) {
  14. this.userId = userId;
  15. this.realName = realName;
  16. }
  17. }

2.jpaRespority中查询代码

  1. @Query(value = "select new com.common.dto.UserDto("
  2. + "s.id,s.realName) FROM User s WHERE "
  3. + "s.departmentCode = ?1 AND s.locked = false AND s.del = false")
  4. List<UserDto> findDepartment(String departmentCode);

其中User 为用户表实体,com.common.dto为UserDto的路径

二、sum,count等字段返回

这种字段没有对应的列明,在dto中无法定义JsonProperty,这时可以不指定列名。具体如下:
1.接收数据的dto格式及参数如下:

  1. public class ExperimenterDetectionRecordDataDto {
  2. /**
  3. * 检测结果
  4. */
  5. private Long sumDetection;
  6. /**
  7. * 检测费用
  8. */
  9. private BigDecimal sumFee;
  10. public ExperimenterDetectionRecordDataDto(Long sumDetection, BigDecimal sumFee) {
  11. this.sumDetection = sumDetection;
  12. this.sumFee = sumFee;
  13. }
  14. public Long getSumDetection() {
  15. return sumDetection;
  16. }
  17. public BigDecimal getSumFee() {
  18. return sumFee;
  19. }
  20. public void setSumDetection(Long sumDetection) {
  21. this.sumDetection = sumDetection;
  22. }
  23. public void setSumFee(BigDecimal sumFee) {
  24. this.sumFee = sumFee;
  25. }
  26. public ExperimenterDetectionRecordDataDto() {
  27. }
  28. }

2.jpaRepository中的sql

  1. @Query(value = "SELECT new com.XXX.detection.model.entrust.ExperimenterDetectionRecordDataDto(SUM(detectionNumber), SUM(totalFee)) FROM ExperimenterDetectionRecord WHERE testerId IN ?1 AND del = FALSE AND completed = TRUE AND completeExperimentDate BETWEEN ?2 AND ?3 GROUP BY testerId")
  2. List<ExperimenterDetectionRecordDataDto> findDetectionRecordAndTime(List<String> testId, Date startTime, Date endTime);

如果是有的是有字段,有的没有,也可以使用Object来接收,此时不需要定义dto,直接接收,jpaRepository代码如下:

  1. @Query(value = "SELECT testerId, SUM(detectionNumber), SUM(totalFee) FROM ExperimenterDetectionRecord WHERE testerId IN ?1 AND del = FALSE AND completed = TRUE AND completeExperimentDate BETWEEN ?2 AND ?3 GROUP BY testerId")
  2. List<Object> findDetectionRecordAndTime(List<String> testId, Date startTime, Date endTime);

发表评论

表情:
评论列表 (有 0 条评论,764人围观)

还没有评论,来说两句吧...

相关阅读

    相关 JPA定义查询

    在使用JPA过程中,写nativeQuery无法满足所有需求,只能寻求其他的途径,下面是一种方法 / 增加过滤条件 @return