繁体   English   中英

如何使用 JPA 存储库将涉及来自多个表的列的本机查询结果的结果 map 转换为自定义 class?

[英]How to map the result from a native query result involving columns from multiple table into a Custom class using JPA Repository?

我确实试图找到一些类似的问题,但我无法理解我的问题。 我有一个如下的存储库

@Repository
public interface CartRepository extends JpaRepository<Cart, Long> {

    @Query(value = "Select i.item_desc, i.item_name ,sum(price) as price, count(*) as quantity from items  i, cart_items ci, cart c where ci.items_item_id=i.item_id and c.id = ci.cart_id and c.user_id = :userId group by ci.items_item_id", nativeQuery = true)
    public List<Object> getCartItemsForCustomer(long userId);

}

查询结果将有四个字段,item_desc、item_name、price 和数量。

我制作了一个 DTO class 以将结果作为 DTO object 的列表返回。

public class CartItemDto {

   private String itemName;
   private String itemDesc;
   private Long price;
   private Integer quanity;
}

我不明白如何将 Map 的结果转换为自定义 dto class。

List<Object> objs = cartRepository.getCartItemsForCustomer(userId);

请建议将对象列表转换为自定义 class 列表的方法。

您可以使用基于接口的投影来解决这个问题,如下所示:

@Query(value = "Select i.item_desc as itemDesc, i.item_name as itemName, sum(price) as price, count(*) as quantity from items  i, cart_items ci, cart c where ci.items_item_id=i.item_id and c.id = ci.cart_id and c.user_id = ?1 group by ci.items_item_id", nativeQuery = true)
public List<CartItemInterface> getCartItemsForCustomer(long userId);

购物车项目界面

public interface CartItemInterface {

    String getItemDesc();
    String getItemName();
    Long getPrice();
    Integer getQuantity();
}

您可以使用 DTO 投影和 map 列到 Java Object。

  • 您需要创建一个接受这四个字段并创建 object 的构造函数。
  • 更改 select 查询以提供 class 的完全限定名称并调用其构造函数。

注意:如果您使用的是 static class,则使用 $ 而不是 (.)

public class CartItemDto {
   private String itemName;
   private String itemDesc;
   private Long price;
   private Integer quanity;
   public CartItemDto(String itemName, String itemDesc, Long price, Integer quanity) {
      this.itemName = itemName;
      this.itemDesc = itemDesc;
      this.price = price;
      this.quantity = quantity;
   }   

}

现在更新查询以实例化结果集中每一行的 dto object 并返回 CartItemDto 对象列表。

@Query(value = "Select new com.package.CartItemDto(i.item_desc, i.item_name ,sum(price), count(*)) from items  i, cart_items ci, cart c where ci.items_item_id=i.item_id and c.id = ci.cart_id and c.user_id = :userId group by ci.items_item_id")
    public List<CartItemDto> getCartItemsForCustomer(long userId);

注意:这不适用于本机查询。 您需要更新查询并将列名和表名更改为字段和实体名称。 还将 nativeQuery 标志更改为 false(默认情况下为 false,因此只需将其删除)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM