Ответ 1
Это старый вопрос, но давайте пример:
С CriteriaBuilder
, в отличие от Hibernate, вы всегда начинаете с типа результата, который вы хотите запросить, а затем конструируете проекцию.
CriteriaBuilder cb = em.getCriteriaBuilder();
//We want Integer result
CriteriaQuery<Integer> cq = cb.createQuery(Integer.class);
//The root does not need to match the type of the result of the query!
Root<Islem> isr = cq.from(Islem.class);
//Create a join to access the variable status of working day
Join<Islem,WorkingDay> join = isr.join("workingDay",JoinType.INNER);
//Create the sum expression
Expression<Integer> sum = cb.sum(isr.get("amount"));
cq.where(
cb.equal(isr.get("currency"), CURRENCY),
cb.notEqual(isr.get("status"), INACTIVE),
cb.equal(isr.get("product"), product),
cb.equal(join.get("status"), ACTIVE)
).select(sum);
С другой стороны, если вы хотите запросить фактические значения "суммы", вы можете сделать:
CompoundSelection<Integer> projection = cb.construct(Integer.class, cb.sum(isr.get("amount")));
cq.where(..).select(projection);
List<Integer> amounts = em.createQuery(cq).getResultList();