Narrowing the result set with the Criteria
The add() method add the restriction for a criteria query.
Criteria dogs = sess.createCriteria(Dog.class);
dogs.add( Restrictions.like("name", "Tommy%") );
dogs.add( Restrictions.between("weight", minWeight, maxWeight) );
List result = dogs.list();
// Restrictions can be classified logically using hibernate criteria basic query.
Criteria dogs = sess.createCriteria(Dog.class);
dogs.add( Restrictions.like("name", "Tommy%") );
dogs.add( Restrictions.or( Restrictions.eq( "age", new Integer(0) ),
Restrictions.isNull("age") ) );
List result = dogs.list();
Sorting the result set with Criteria
The org.hibernate.criterion.Order in the Criteria API uses the Organize class to order your result set by one of the properties of your object, either in ascending or descending order.
Criteria dogs= sess.createCriteria(Dog.class);
dogs.add( Restrictions.like("name", "T%");
dogs.addOrder( Order.asc("name") );
dogs.addOrder( Order.desc("age") );
dogs.setMaxResults(30);
List result = dogs.list();
Associations with Criteria
Restrictions can be imposed on entities that are associated by browsing associations using createCriteria():
Criteria dogs = sess.createCriteria(Dog.class);
dogs.add( Restrictions.like("name", "T%") );
dogs.createCriteria("puppy");
dogs.add( Restrictions.like("name", "T%") );
List result = dogs.list();
Projections, aggregation, and grouping
The org.hibernate.criterion.Projections provides a factory for Projection instances. A projection can be applied by executing setProjection() on a query.
Example 1:
Criteria dogs = session.createCriteria(Dog.class);
dogs.setProjection( Projections.rowCount() );
dogs.add( Restrictions.eq("color", Color.WHITE) );
List result = dogs.list();
Example 2:
Criteria dogs = session.createCriteria(Dog.class);
dogs.setProjection( Projections.rowCount() );
dogs.setProjection( Projections.avg("weight") );
dogs.setProjection( Projections.max("weight") );
dogs.setProjection(Projections.groupProperty("color") );
List result = dogs.list()
Pagination using criteria
The Criteria interface offers two options for pagination.
1. public Criteria setFirstResult(int fr): This method accepts an integer that represents row 0, which is the first row in the result set.
2. public Criteria setMaxResults(int mr): This function tells Hibernate how many mr objects to retrieve.
Criteria cr = session.createCriteria(Dog.class);
cr.setFirstResult(1);
cr.setMaxResults(10);
List results = cr.list();
Example Queries
With the help of the org.hibernate.criterion.Example class, you can create a hibernate criteria basic query from an existing instance.
Example example = Example.create(dog);
example.excludeZeroes(); // exclude properties with zero values
example.excludeProperty("color"); // exclude the attribute "colour"
example.ignoreCase() ; //compare strings without taking case into account
example.enableLike(); //use like for comparing string
List results = session.createCriteria(Dog.class);
results.add(example);
List re = results.list();
Detached queries and subqueries
With the help of the DetachedCriteria class in hibernate criteria basic query, you can construct a query outside the confines of a session and then run it using any Session.
DetachedCriteria avgWeight = DetachedCriteria.forClass(Dog.class);
avgWeight.setProjection( Property.forName("weight").avg() );
Criteria dogs = session.createCriteria(Dog.class);
dogs.add( Property.forName("weight").gt(avgWeight) );
List result = dogs.list();
Frequently Asked Questions
What are the differences between Heap and Stack Memory in Java?
The stack is frequently used to track local variables and methods' execution order. On the other side, objects are stored in heap memory. After holding, they use dynamic memory allocation and deallocation.
Can you set Hibernate's Entity class as final?
The proxy pattern is used by hibernate for lazy initialization; therefore, while you can declare an entity class as final, doing so is not advised. Hibernate won't be able to create subclasses or use the proxy pattern if you declare an entity class as final, which will limit your performance options.
What is Projection in Hibernate?
The "projection" resembles picking out the specific data you require so that NHibernate only requests that specific data from the database when it creates the SQL.
What is lazy loading in hibernate?
Hibernate's lazy loading enhances performance. The child objects are loaded as needed.
Lazy loading is now enabled by default in Hibernate 3; therefore lazy="true" is not necessary. It refers to not loading the child's objects while loading the parent.
Conclusion
Congratulations on reaching the end! In this blog, we have discussed Hibernate criteria basic query to restrict, sort, associate, and group the resultant set with examples.
Hope you liked this blog of Hibernate criteria basic query; it has added some new information to your coding journey. Please look at these similar topics to learn more: Hibernate Interview Questions, Structured Query Language, Learning SQL, Database Languages, and Microservice in Java.
Refer to our Coding Ninjas Studio Guided Path to learn Data Structures and Algorithms, Competitive Programming, JavaScript, System Design, and even more! You can also check out the mock test series and participate in the contests hosted by Coding Ninjas Studio!
But if you're just starting and want to learn about questions posed by tech giants like Amazon, Microsoft, Uber, and so on. In such a case, for placement preparations, you can also look at the problems, interview experiences, and interview bundle.
Please upvote our blogs if you find them useful and exciting!
Happy Learning!