From 35c4ec821e600b0d2264a5cf378753551af7ff80 Mon Sep 17 00:00:00 2001 From: George Kalampokis Date: Wed, 20 Oct 2021 12:40:44 +0300 Subject: [PATCH] Add a special query logic with group by and count --- .../QueryableHibernateList.java | 19 +++++++++++++++++-- 1 file changed, 17 insertions(+), 2 deletions(-) diff --git a/dmp-backend/queryable/src/main/java/eu/eudat/queryable/jpa/hibernatequeryablelist/QueryableHibernateList.java b/dmp-backend/queryable/src/main/java/eu/eudat/queryable/jpa/hibernatequeryablelist/QueryableHibernateList.java index a347e3a2b..75cad534f 100644 --- a/dmp-backend/queryable/src/main/java/eu/eudat/queryable/jpa/hibernatequeryablelist/QueryableHibernateList.java +++ b/dmp-backend/queryable/src/main/java/eu/eudat/queryable/jpa/hibernatequeryablelist/QueryableHibernateList.java @@ -164,8 +164,16 @@ public class QueryableHibernateList implements QueryableLi if (distinct) criteriaQuery.select(criteriaBuilder.countDistinct(this.root.get("id"))); else criteriaQuery.select(criteriaBuilder.count(this.root)); criteriaQuery.where(this.generateWherePredicates(this.singlePredicates, this.root, this.nestedPredicates, this.nestedQueryRoot)); + if (!this.groupings.isEmpty()) criteriaQuery.groupBy(this.generateGroupPredicates(this.groupings, this.root)); //if (distinct) criteriaQuery.distinct(true); - return this.manager.createQuery(criteriaQuery).getSingleResult(); + + //GK: Group By special case. When group by is used, since it will result in a list of how many elements have the grouped field common + // then it will instead return the number of the distinct values of the grouped field + if (this.groupings.isEmpty()) { + return this.manager.createQuery(criteriaQuery).getSingleResult(); + } else { + return (long) this.manager.createQuery(criteriaQuery).getResultList().size(); + } } @Async @@ -176,8 +184,15 @@ public class QueryableHibernateList implements QueryableLi if (distinct) criteriaQuery.select(criteriaBuilder.countDistinct(this.root.get("id"))); else criteriaQuery.select(criteriaBuilder.count(this.root)); criteriaQuery.where(this.generateWherePredicates(this.singlePredicates, this.root, this.nestedPredicates, this.nestedQueryRoot)); + if (!this.groupings.isEmpty()) criteriaQuery.groupBy(this.generateGroupPredicates(this.groupings, this.root)); //if (distinct) criteriaQuery.distinct(true); - return CompletableFuture.supplyAsync(() -> this.manager.createQuery(criteriaQuery).getSingleResult()); + return CompletableFuture.supplyAsync(() -> { + if (this.groupings.isEmpty()) { + return this.manager.createQuery(criteriaQuery).getSingleResult(); + } else { + return (long) this.manager.createQuery(criteriaQuery).getResultList().size(); + } + }); }