zoukankan      html  css  js  c++  java
  • springboot~@Query到DTO对象

    我们有时在进行开发过程中,使用jpa的@Query注解去选择多张表然后返回一个DTO对象,这个时候我们需要特殊处理一下,因为默认情况下,你的jpa代码是不认DTO对象的。

    参考文章:https://smarterco.de/spring-data-jpa-query-result-to-dto/

    • entity实体
    @Entity
    @Getter
    @Setter
    @Builder
    @ToString
    @AllArgsConstructor
    @NoArgsConstructor
    public class OrderInfo extends EntityBase {
      @Id
      @GeneratedValue
      private int id;
    
      private int userId;
    
      private String userName;
    
      private double total;
    
      private String shippingName;
    
      private String shippingAddress;
    
      private Date orderTime;
    }
    
    @Entity
    @Getter
    @Setter
    @Builder
    @ToString
    @AllArgsConstructor
    @NoArgsConstructor
    public class OrderItem extends EntityBase {
      @Id
      @GeneratedValue
      private int id;
    
      private int orderId;
    
      private int productId;
    
      private String productName;
    
      private int count;
    
      private double salePrice;
    }
    /**
     * DTO对象
     */
    @Getter
    @Setter
    @Builder
    @ToString
    @AllArgsConstructor
    @NoArgsConstructor
    public class OrderList {
      public int id;
    
      private int userId;
    
      private String userName;
    
      private int productId;
    
      private String productName;
    
      private int count;
    
      private double salePrice;
    
    }
    
    • repository方法
      @Query("select new com.lind.microservice.productCenter.dto.OrderList" +
          "( o.id,o.userId,o.userName,oi.productId,oi.productName,oi.count,oi.salePrice) " +
          " from OrderInfo o " +
          " join OrderItem oi on o.id=oi.orderId")
      List<OrderList> getOrderInfos();
    
    • 结果
    [
    {
    "id": 5,
    "userId": 3,
    "userName": "lind",
    "productId": 4,
    "productName": "足球",
    "count": 1,
    "salePrice": 99
    }
    ]
    
  • 相关阅读:
    [HDU 3038] How Many Answers Are Wrong
    [BZOJ 4977][Lydsy1708月赛]跳伞求生
    [BZOJ4974] 字符串大师
    总结-exCRT
    [luogu 4777] exCRT
    [AHOI 2009] 中国象棋
    JavaScript MVC框架PK:Angular、Backbone、CanJS与Ember
    十一黄金周 加班加点随笔
    从两个设计模式到前端MVC-洪宇
    Todo&Rocket
  • 原文地址:https://www.cnblogs.com/lori/p/9409010.html
Copyright © 2011-2022 走看看