Hibernate groupby criteria and HQL query Example

PROGRAMMINGJava ExamplesC Examples
Java Examples
C Examples
C Tutorials
aws
JAVAEXCEPTIONSCOLLECTIONSSWINGJDBC
EXCEPTIONS
COLLECTIONS
SWING
JDBC
JAVA 8
SPRING
SPRING BOOT
HIBERNATE
PYTHON
PHP
JQUERY
PROGRAMMINGJava ExamplesC Examples
Java Examples
C Examples
C Tutorials
aws
Here I m going to show how to read the data from database using hibernate groupby expression.
I have a simple Item class which represents different items with categories. I am going to read data with a count of items for each category using groupby expression.
Hibernate core 5.2.2
Java 8
<dependency>
     <groupId>org.hibernate</groupId>
     <artifactId>hibernate-core</artifactId>
     <version>5.2.12.Final</version>
</dependency>
Item.class, which represents an Item.
package com.onlinetutorialspoint.entity;

import javax.persistence.*;

@Entity
@Table(name="item")
public class Item {

    @Id
    @GeneratedValue(strategy= GenerationType.AUTO)
    @Column(name="id")
    private int itemId;
    @Column(name="item_name",length=30)
    private String itemName;
    @Column(name="category",length=30)
    private String itemCategory;
    @Column(name="item_price")
    private double itemPrice;

    public Item() {
    }

    public Item(String itemName, String itemCategory, double itemPrice) {
        this.itemName = itemName;
        this.itemCategory = itemCategory;
        this.itemPrice = itemPrice;
    }

    public int getItemId() {
        return itemId;
    }

    public void setItemId(int itemId) {
        this.itemId = itemId;
    }

    public String getItemName() {
        return itemName;
    }

    public void setItemName(String itemName) {
        this.itemName = itemName;
    }

    public String getItemCategory() {
        return itemCategory;
    }

    public void setItemCategory(String itemCategory) {
        this.itemCategory = itemCategory;
    }

    public double getItemPrice() {
        return itemPrice;
    }

    public void setItemPrice(double itemPrice) {
        this.itemPrice = itemPrice;
    }
}

HibernateUtil.java responsible to provide Hibernate Session Factory object.
package com.onlinetutorialspoint.util;

import org.hibernate.SessionFactory;
import org.hibernate.boot.Metadata;
import org.hibernate.boot.MetadataSources;
import org.hibernate.boot.registry.StandardServiceRegistry;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;

public class HibernateUtil {
  private static StandardServiceRegistry standardServiceRegistry;
  private static SessionFactory sessionFactory;

  static{
      if (sessionFactory == null) try {
      standardServiceRegistry = new StandardServiceRegistryBuilder()
          .configure()
          .build();
      MetadataSources metadataSources = new MetadataSources(standardServiceRegistry);
      Metadata metadata = metadataSources.getMetadataBuilder().build();
      sessionFactory = metadata.getSessionFactoryBuilder().build();
    } catch (Exception e) {
      e.printStackTrace();
      if (standardServiceRegistry != null) {
        StandardServiceRegistryBuilder.destroy(standardServiceRegistry);
      }
    }
  }
  public static SessionFactory getSessionFactory() {
    return sessionFactory;
  }
}
Here we are using CriteriaQuery Interface to make the group by functionality.
public static void groupByCriteria(){
    try (Session session = HibernateUtil.getSessionFactory().openSession()) {

        CriteriaBuilder builder = session.getCriteriaBuilder();

        CriteriaQuery<Object[]> criteriaQuery = builder.createQuery(Object[].class);
        Root<Item> root = criteriaQuery.from(Item.class);
        criteriaQuery.multiselect(root.get("itemCategory"),builder.count(root.get("itemCategory")));
        criteriaQuery.groupBy(root.get("itemCategory"));
        Query<Object[]> query = session.createQuery(criteriaQuery);

        List<Object[]> resultList = query.getResultList();
        resultList.forEach(item-> System.out.println("Category : "+item[0]+"\t count : "+item[1]));

    } catch (Exception e) {
        e.printStackTrace();
    }
}
mysql> select category, count(category) from item group by category;
Hibernate: select item0_.category as col_0_0_, count(item0_.category) as col_1_0_ from item item0_ group by item0_.category
Category : Books	 count : 4
Category : Laptop	 count : 5
Category : Mobiles	 count : 6
We can even apply having clause on criteria query on top of groupby function like below.
public static void groupByCriteria(){
        try (Session session = HibernateUtil.getSessionFactory().openSession()) {

            CriteriaBuilder builder = session.getCriteriaBuilder();

            CriteriaQuery<Object[]> criteriaQuery = builder.createQuery(Object[].class);
            Root<Item> root = criteriaQuery.from(Item.class);
            criteriaQuery.multiselect(root.get("itemCategory"),builder.count(root.get("itemCategory")));
            criteriaQuery.groupBy(root.get("itemCategory"));
            criteriaQuery.having(builder.greaterThan(builder.sum(root.get("itemPrice")), 70000.00));
            Query<Object[]> query = session.createQuery(criteriaQuery);

            List<Object[]> resultList = query.getResultList();
            resultList.forEach(item-> System.out.println("Category : "+item[0]+"\t count : "+item[1]));

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
Hibernate: select item0_.category as col_0_0_, count(item0_.category) as col_1_0_ from item item0_ group by item0_.category having sum(item0_.item_price)>70000.0
Category : Laptop	 count : 5
Category : Mobiles	 count : 6
public static void groupByHQL(){
    try (Session session = HibernateUtil.getSessionFactory().openSession()) {
        Query query = session.createQuery("SELECT i.itemCategory, COUNT(i.itemCategory) " +
                "FROM Item i GROUP BY i.itemCategory");
        List<Object[]> list = query.getResultList();
        list.forEach(item-> System.out.println("Category : "+item[0]+"\t count : "+item[1]));
    } catch (Exception e) {
        e.printStackTrace();
    }
}
Hibernate: select item0_.category as col_0_0_, count(item0_.category) as col_1_0_ from item item0_ group by item0_.category
Category : Books	 count : 4
Category : Laptop	 count : 5
Category : Mobiles	 count : 6
public static void groupByWithHavingHQL(){
        try (Session session = HibernateUtil.getSessionFactory().openSession()) {
            Query query = session.createQuery("SELECT i.itemCategory, COUNT(i.itemCategory), SUM(i.itemPrice) " +
                    "FROM Item i GROUP BY i.itemCategory HAVING SUM(i.itemPrice) > 70000");
            List<Object[]> list = query.getResultList();
            list.forEach(item-> System.out.println("Category : "+item[0]+"\t count : "+item[1]));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
Hibernate: select item0_.category as col_0_0_, count(item0_.category) as col_1_0_, sum(item0_.item_price) as col_2_0_ from item item0_ group by item0_.category having sum(item0_.item_price)>70000
Category : Laptop	 count : 5
Category : Mobiles	 count : 6
Hibernate Docs Criteria
Hibernate CriteriaQuery Examples
Hibernate HQL Examples
Happy Learning 🙂

Hibernate Left Join Example
Hibernate Right Join Example
Many to One Mapping in Hibernate Example
Hibernate One To Many Example (XML Mapping)
Hibernate orderby criteria Example
Calling Stored Procedures in Hibernate
Hibernate Filter Example Xml Configuration
Hibernate Criteria API with Example
hibernate update query example
Hibernate Native SQL Query Example
Hibernate Named Query with Example
Hibernate Query Language (HQL) Select Operation
HQL update, delete Query Example
Hibernate Download and Setup
Hibernate Pagination Example

Hibernate Left Join Example
Hibernate Right Join Example
Many to One Mapping in Hibernate Example
Hibernate One To Many Example (XML Mapping)
Hibernate orderby criteria Example
Calling Stored Procedures in Hibernate
Hibernate Filter Example Xml Configuration
Hibernate Criteria API with Example
hibernate update query example
Hibernate Native SQL Query Example
Hibernate Named Query with Example
Hibernate Query Language (HQL) Select Operation
HQL update, delete Query Example
Hibernate Download and Setup
Hibernate Pagination Example
 


Δ
 Hibernate – Introduction
 Hibernate – Advantages
 Hibernate – Download and Setup
 Hibernate – Sql Dialect list
 Hibernate – Helloworld – XML
 Hibernate – Install Tools in Eclipse
 Hibernate – Object States
 Hibernate – Helloworld – Annotations
 Hibernate – One to One Mapping – XML
 Hibernate – One to One Mapping foreign key – XML
 Hibernate – One To Many -XML
 Hibernate – One To Many – Annotations
 Hibernate – Many to Many Mapping – XML
 Hibernate – Many to One – XML
 Hibernate – Composite Key Mapping
 Hibernate – Named Query
 Hibernate – Native SQL Query
 Hibernate – load() vs get()
 Hibernate Criteria API with Example
 Hibernate – Restrictions
 Hibernate – Projection
 Hibernate – Query Language (HQL)
 Hibernate – Groupby Criteria HQL
 Hibernate – Orderby Criteria
 Hibernate – HQLSelect Operation
 Hibernate – HQL Update, Delete
 Hibernate – Update Query
 Hibernate – Update vs Merge
 Hibernate – Right Join
 Hibernate – Left Join
 Hibernate – Pagination
 Hibernate – Generator Classes
 Hibernate – Custom Generator
 Hibernate – Inheritance Mappings
 Hibernate – Table per Class
 Hibernate – Table per Sub Class
 Hibernate – Table per Concrete Class
 Hibernate – Table per Class  Annotations
 Hibernate – Stored Procedures
 Hibernate – @Formula Annotation
 Hibernate – Singleton SessionFactory
 Hibernate – Interceptor
 hbm2ddl.auto Example in Hibernate XML Config
 Hibernate – First Level Cache