As multiple hibernate 5 API’s like createSQLQuery, Query and createCriteria deprecated, I have provided the below snippet which performs the multiselect with groupby count using Hibernate latest API’s.
Table of Contents
Multiselect in hibernate criteriaQuery
criteriaQuery.multiselect(Store.get("storeType"),criteriaBuilder.count(StoreRoot));
groupBy in Hibernate criteriaBuilder
criteriaQuery.groupBy(storeRoot.get("storeType"));
count in Hibernate criteriaBuilder
criteriaBuilder.count(StoreRoot);
Hibernate multiselect with groupBy count – Code Snippet
// if you have different way to get the session, just replace that with this line. Session session = entityManager.getSession(); CriteriaBuilder criteriaBuilder = session.getCriteriaBuilder(); CriteriaQuery<Object[]> criteriaQuery = criteriaBuilder.createQuery(Object[].class); Root<Store> storeRoot = criteriaQuery.from(Store.class); criteriaQuery.multiselect(Store.get("storeType"),criteriaBuilder.count(StoreRoot)); criteriaQuery.groupBy(storeRoot.get("storeType")); List<Object[]> result = session.createQuery(criteriaQuery).getResultList();