首页 > 解决方案 > Spring JPA Query - 替换结果集中的负值

问题描述

我正在使用 Spring Data JPA 开发一个 Spring Boot 应用程序。我正在使用自定义 JPQL 查询来获取我需要的数据。

以下是我的方法存储库:

/**
  * SELECT sku, SUM(real_allocation - logical_allocation)
  * FROM stock
  * WHERE warehouse_brand = '?'
  * GROUP BY (warehouse_brand, sku);
  */

@Query(value = "SELECT new it.reply.retail.oms.common.api.inventory.CumulativeInventoryItem " +
               "(s.pk.sku, SUM(s.realAllocation - s.logicalAllocation)) " +
               "FROM Stock s WHERE s.pk.whsCode IN :warehouses GROUP BY (s.pk.sku)")
Page<CumulativeInventoryItem> getCumulativeInventory(List<String> warehouses, Pageable pageable);

CumulativeInventoryItem定义对象如下:

public class CumulativeInventoryItem {

    private String sku;
    private Long cumulativeQty;

}

cumulativeQty我获得的结果集有时包含需要用 0 替换的属性的负值。

是否可以使用临时查询替换这些值,或者一旦我从 JPA 方法中获取结果集后我需要替换它们?

标签: javaspring-bootspring-data-jpa

解决方案


据此:https ://en.wikibooks.org/wiki/Java_Persistence/JPQL_BNF#New_in_JPA_2.0

CASE WHEN THEN ELSE 组合可以在那里使用。

可以试试吗

SUM(CASE WHEN (s.realAllocation - s.logicalAllocation < 0) THEN 0 ELSE (s.realAllocation - s.logicalAllocation)))

代替

SUM(s.realAllocation - s.logicalAllocation)

推荐阅读