Criteria API in Hibernate helps developers to build dynamic criteria queries on the persistence database. Criteria API is a more powerful and flexible alternative to HQL (Hibernate Query Language) queries for creating dynamic queries.
This API allows to programmatically development criteria query objects. The org.hibernate.Criteria interface is used for these purposes. The Session interface of hibernate framework has createCriteria() method that takes the persistent object’s class or its entity name as the parameters and returns persistence object instance the criteria query is executed.
It also makes it very easy to incorporate restrictions to selectively retrieve data from the database. It can be achieved by using the add() method which accepts the org.hibernate.criterion.Criterion object representing individual restriction.
To return all the data of InterviewBitEmployee entity class.
Criteria criteria = session.createCriteria(InterviewBitEmployee.class); Listresults = criteria.list(); To retrive objects whose property has value equal to the restriction, we use Restrictions.eq() method. For example, to fetch all records with name ‘Hibernate’:
Criteria criteria= session.createCriteria(InterviewBitEmployee.class); criteria.add(Restrictions.eq("fullName","Hibernate")); Listresults = criteria.list(); To get objects whose property has the value “not equal to” the restriction, we use Restrictions.ne() method. For example, to fetch all the records whose employee’s name is not Hibernate:
Criteria criteria= session.createCriteria(InterviewBitEmployee.class); criteria.add(Restrictions.ne("fullName","Hibernate")); Listresults = criteria.list() To retrieve all objects whose property matches a given pattern, we use Restrictions.like() (for case sensitivenes) and Restrictions.ilike()(for case insensitiveness)
Criteria criteria= session.createCriteria(InterviewBitEmployee.class); criteria.add(Restrictions.like("fullName","Hib%",MatchMode.ANYWHERE)); Listresults = criteria.list(); Similarly, it also has other methods like isNull(), isNotNull(), gt(), ge(), lt(), le() etc for adding more varieties of restrictions. It has to be noted that for Hibernate 5 onwards, the functions returning an object of typeCriteria are deprecated. Hibernate 5 version has provided interfaces like CriteriaBuilder and CriteriaQuery to serve the purpose:
// Create CriteriaBuilder CriteriaBuilder builder = session.getCriteriaBuilder();
// Create CriteriaQuery CriteriaQuerycriteria = builder.createQuery(YourClass.class); For introducing restrictions in CriteriaQuery, we can use the CriteriaQuery.where method which is analogous to using the WHERE clause in a JPQL query.