【问题标题】:CriteriaBuilder - Sum using SelectCaseCriteriaBuilder - 使用 SelectCase 求和
【发布时间】:2012-07-12 23:48:10
【问题描述】:

我正在尝试执行如下求和 SQL 查询:

select group_ID, sum(case when user_type = 'Exec' then 1000  
                          when user_type = 'Office' then 10 else 0 end)  
from subscription  
group by group_ID;  

使用来自休眠 CriteriaBuilder 查询的以下 sn-p:

criteriaBuilder.sum(
  criteriaBuilder.selectCase()  
     .when(criteriaBuilder.equal(subscriptionJoin.get(Subscription_.userType), "Exec"),1000)  
     .when(criteriaBuilder.equal(subscriptionJoin.get(Subscription_.userType), "Office"),1)  
     .otherwise(101))  

但是出现以下编译错误:

类型参数“N”的推断类型“java.lang.object”不在其范围内;应该扩展'java.lang.number'

知道如何支持使用 selectCase 执行求和吗?

【问题讨论】:

    标签: criteria-api


    【解决方案1】:

    Sum 定义如下:

    <N extends Number> Expression<N> sum(Expression<N> x);
    

    所以编译错误的原因是 sum 方法期望这样的参数是 Expression 类型扩展 Number。它从 selectCase 中确定类型并以 java.lang.Object 结束,这是不可接受的。

    问题可以通过给出类型参数来解决(&lt;Number&gt;):

    criteriaBuilder.sum(
      criteriaBuilder.<Number>selectCase()
    

    【讨论】:

    • 非常感谢您提供的解决方案,Mikko。这种方法是否比将 .as(Number.class) 后缀添加到 selectCase() 更可取。
    • 这只是意见问题,我更喜欢使用语言构造而不是调用 as-method,这也是因为它要求的代码更少。因为这个答案提供了解决方案,所以唯一要做的就是接受答案:meta.stackexchange.com/a/5235/171185
    【解决方案2】:

    我们在我们的项目中使用 Spring Data JPA,我有同样的情况需要进行求和。我只是遵循“命名参数”方法而不是条件查询,因为这种方法看起来很简单。

    我给我求和的方法如下。

        public interface ITransactionEntryRepo extends PagingAndSortingRepository<TransactionEntryEntity, String> {
    
            @Query("select SUM(CASE WHEN te.debit = 'Y' THEN (te.amount * - 1) WHEN te.debit = 'N' THEN te.amount ELSE 0 END) AS availablebalance FROM TransactionEntity t, TransactionEntryEntity te WHERE t.id = te.transactionEntity.id and te.accountEntity.id = :id and te.valid = 'T' and t.retcode = 'XX' GROUP BY te.accountEntity.id")
                public double findAvailableBalance(@Param("id") String id);
    }
    

    我在需要的类中调用这个方法

    double balance = iTransactionEntryRepo.findAvailableBalance(accountEntity.getId());
    

    并将它(平衡)传递到我需要的任何地方。希望这对某人有所帮助。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-08-04
      • 1970-01-01
      • 2019-04-10
      • 1970-01-01
      • 2012-02-29
      • 1970-01-01
      相关资源
      最近更新 更多