InterviewSolution
| 1. |
What is criteria API in hibernate? |
|
Answer» 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. Usage examples: To return all the data of InterviewBitEmployee entity class. Criteria criteria = session.createCriteria(InterviewBitEmployee.class);List<InterviewBitEmployee> results = 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"));List<InterviewBitEmployee> results = 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"));List<Employee> results = 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));List<InterviewBitEmployee> results = 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: javax.persistence.criteria.CriteriaBuilderjavax.persistence.criteria.CriteriaQuery// Create CriteriaBuilderCriteriaBuilder builder = session.getCriteriaBuilder();// Create CriteriaQueryCriteriaQuery<YourClass> criteria = 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. |
|