< Prev
Next >



Retrieving a record - CriteriaQuery



In our last article, we introduced you to the concept of CriteriaQuery API and how to use it to retrieve all the records(objects of a class) stored in a database table. Today, we are going to show you how to retrieve a particular record(object) stored in a database table using the CriteriaQuery API.

For those, who don't know the steps 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();

    or,

    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

Ad2