< Prev

Retrieving min,max,count, avg from records

In our last article, you saw how to retrieve records of a database table(mapped from a class) in an ascending and descending order using the CriteriaQuery API. Today, we are going to show you how to retrieve the maximum, minimum and average of all values in a column mapped to a property named salary and finally retrieving the total count of records in the same database table using CriteriaQuery API.

For those, who don't know the steps to use the CriteriaQuery API, we are going to explain the important steps once again in this article.

Steps to use the CriteriaQuery

Let's say that we want to query a class named UserInfo.

  1. Creating the CriteriaBuilder from the Session object.

  2. SessionFactory sf=  new Configuration().configure().buildSessionFactory();  
    Session session = sf.openSession();
    CriteriaBuilder cb = session.getCriteriaBuilder();

  3. Creating the CriteriaQuery of an Object type using the CriteriaBuilder object.

  4. CriteriaQuery<Object> crtQ = cb.createQuery(Object.class);

  5. Creating the Root collection of a type of objects. Root allows us to define attributes in the query, later on.

  6. Root<UserInfo> root = crtQ.from(UserInfo.class);

  7. Specifying the item to be returned in the query result(using Root) i.e. objects of a type referenced by Root.


  9. Using the Session object to create a Query object to execute the query.

  10. Query query = session.createQuery(crtQ);

  11. Executing the Query to get a particular type of collection of records in a List.

  12. List<UserInfo> collection2 = query.getResultList();


    Executing the Query to get a single value result then we would call a getSingleResult() method and store the result in an Object.

    Object object = query.getSingleList();

Let's understand the CriteriaQuery through an example in the upcoming section.

Note :

Please Subscribe

Please subscribe to our social media channels for daily updates.

Decodejava Facebook Page  DecodeJava Twitter Page Decodejava Google+ Page



Please check our latest addition