Hibernate Framework HQL and Criteria API 2 — Questions and Answers
Question 1: Which Hibernate API allows building queries programmatically without writing HQL strings?
- Criteria API (Correct answer)
- Query Builder
- JPQL Builder
- QueryDSL
Correct answer: Criteria API
The Criteria API provides a type-safe, programmatic way to build Hibernate queries without writing query strings.
Question 2: Which class is the entry point for creating a CriteriaQuery in JPA/Hibernate?
- CriteriaBuilder (Correct answer)
- CriteriaFactory
- QueryBuilder
- CriteriaSession
Correct answer: CriteriaBuilder
CriteriaBuilder is obtained from the EntityManager and is used to create CriteriaQuery, Predicate, and expression objects.
Question 3: What does the Root<T> object represent in a Criteria query?
- The entity being queried from — the FROM clause (Correct answer)
- The WHERE conditions
- The ORDER BY clause
- The SELECT projection
Correct answer: The entity being queried from — the FROM clause
Root<T> represents the root entity in the FROM clause of a Criteria query, used to navigate to entity fields.
Question 4: Which method adds a WHERE condition to a CriteriaQuery?
- criteriaQuery.where(predicate) (Correct answer)
- criteriaQuery.filter(predicate)
- criteriaQuery.restrict(predicate)
- criteriaQuery.condition(predicate)
Correct answer: criteriaQuery.where(predicate)
The where() method on CriteriaQuery accepts one or more Predicate objects to define the filtering conditions.
Question 5: What is a Predicate in the JPA Criteria API?
- A boolean condition used in WHERE clauses (Correct answer)
- A result transformation
- A join specification
- An ordering rule
Correct answer: A boolean condition used in WHERE clauses
A Predicate represents a boolean expression that can be used in WHERE, HAVING, or join conditions in a Criteria query.
Question 6: Which method executes a CriteriaQuery using the EntityManager?
- entityManager.createQuery(criteriaQuery).getResultList() (Correct answer)
- entityManager.execute(criteriaQuery)
- entityManager.run(criteriaQuery)
- entityManager.find(criteriaQuery)
Correct answer: entityManager.createQuery(criteriaQuery).getResultList()
You pass a CriteriaQuery to createQuery() on the EntityManager, then call getResultList() to execute it and retrieve results.
Which Hibernate API allows building queries programmatically without writing HQL strings?