Advertisement



< Prev
Next >



Hibernate - CriteriaQuery



CriteriaQuery API allows you to specify the criteria or a condition that you want to apply on a class to access its particular object or a collection of objects.

Note : Since Hibernate 5, the Criteria API has been deprecated and hence CriteriaQuery API is used as its replacement to allow us to associate a criteria/condition with a query when accessing the database.

Let's understand the necessary steps to be performed in a sequence, in order to use CriteriaQuery API.




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

Please subscribe to our social media channels for daily updates.


Decodejava Facebook Page  DecodeJava Twitter Page Decodejava Google+ Page




Advertisement



Notifications



Please check our latest addition

C#, PYTHON and DJANGO


Advertisement