< 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 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 property named salaryand 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 CriteriaQuery API, we are going to explain the important steps once again in this article.

Steps to use 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 CriteriaBuilder object.

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

  5. Creating a 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.

  8. crtQ.select(root);

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

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

  11. Executing the Query to get 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 our social media channels for notifications, we post a new article everyday.

Decodejava Google+ Page Decodejava Facebook Page  DecodeJava Twitter Page

Coming Next
C++ and Python