本文介绍了CriteriaBuilder-使用SelectCase求和的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am trying to perform a summation SQL query like the following:

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查询中的以下代码段:

using the following snippet from a hiberate CriteriaBuilder query:

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

但是会出现以下编译错误:

However the following compile error appears:

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

Inferred type 'java.lang.object' for type parameter 'N' is not within its bound; should extend 'java.lang.number'

任何想法如何支持使用selectCase进行求和?

Any idea how to support performing a summation using the selectCase?

推荐答案

总和定义如下:

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

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

So reason to the compilation error is that sum method expect such arguments which is Expression with type that extends Number. It determines type from the selectCase and ends up with java.lang.Object, which is not acceptable.

可以通过提供类型参数来解决问题(< Number> ):

Problem can be solved by giving type parameter (<Number>):

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

这篇关于CriteriaBuilder-使用SelectCase求和的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-13 06:21