Spring Data JPA Repository 在使用 Sum 函数时返回 Object[] 而不是 MyType



直到今天我还在用这个语句:

@Query(value = "select top 5 p.*, sum(po.quantity) as total_quantity from product p " +
        "inner join productorder po " +
            "on p.id = po.product_id " +
        "group by p.id, p.name " +
        "order by total_quantity desc", nativeQuery = true)
List<Product> findTopFiveBestSellerNative();

在这里,当我将返回类型定义为产品列表时,我正好得到了我需要的东西。并且所选列total_quantity将被忽略。

最后,我需要将分页集成到此查询中。由于 Spring 不支持使用本机查询进行分页处理,因此我想首先将此查询转换为 JPQL(然后我将添加分页(。现在它看起来像这样:

@Query(value = "select p, sum(po.quantity) as total_quantity " + 
        "from Product p, ProductOrder po " +
        "where p.id = po.pk.product " +
        "group by p.id, p.name " +
        "order by total_quantity desc")
List<Product> findTopFiveBestSeller();

返回类型现在是对象数组的列表,其中数组的第一个元素是 Product,第二个元素是total_quantity。(尽管方法签名显示列表。

如何更改我的语句或以某种方式实现这一点,这样我就不必处理数组,而只需获取我的 Product 对象?

编辑:我想将此查询用作子查询,然后从子查询中选择产品。事实证明,JPQL 不能在 'from' 子句中执行子查询。

事实上,

您的查询不仅返回构建 Product 对象所需的列,因此 Spring JPA 将其映射到对象。

创建一个扩展产品并包含属性 totalQuantity 的聚合实体,并将查询映射到该实体(可能在另一个存储库中(

最新更新