< Prev
Next >

Retrieving records in an order - CriteriaQuery

In our last article, you saw how to retrieve multiple columns of a database table(mapped from a class) using CriteriaQuery API. Today, we are going to show you how to retrieve all the records of a database table in a descending order/ascending order based on the values of specific property of a class, 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.


  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

Please subscribe to our social media channels for daily updates.

Decodejava Facebook Page  DecodeJava Twitter Page Decodejava Google+ Page



Please check our latest addition