Answer:
Changing Criteria API at runtime means you can build queries dynamically based on conditions only known during execution (e.g., user input, UI filters, request parameters) instead of writing fixed, hardcoded queries.
🔹 Why is this important?
- In real apps, search screens often let users specify any combination of filters (e.g., by username, email, status).
- You don’t want to write separate queries for every combination → you want one flexible query that adjusts based on which filters are provided at runtime.
🔹 How do you do it?
You conditionally add predicates to the Criteria query during runtime, depending on which filter values are present.
🔹 Example: runtime criteria building
Imagine a search form where the user can enter optional filters:
- username
- active status
public List<User> searchUsers(String username, String email, Boolean active) {
Session session = sessionFactory.openSession();
CriteriaBuilder cb = session.getCriteriaBuilder();
CriteriaQuery<User> cq = cb.createQuery(User.class);
Root<User> root = cq.from(User.class);
List<Predicate> predicates = new ArrayList<>();
// Add filters dynamically depending on provided values:
if (username != null && !username.isEmpty()) {
predicates.add(cb.equal(root.get("username"), username));
}
if (email != null && !email.isEmpty()) {
predicates.add(cb.like(root.get("email"), "%" + email + "%"));
}
if (active != null) {
predicates.add(cb.equal(root.get("active"), active));
}
// Combine predicates using AND
cq.select(root).where(cb.and(predicates.toArray(new Predicate[0])));
List<User> results = session.createQuery(cq).getResultList();
session.close();
return results;
}
🔹 What’s happening at runtime?
✅ Only the filters actually provided by the caller are included in the final SQL query.
✅ If a user doesn’t specify email, it’s not part of the WHERE clause.
✅ This lets you handle all combinations of filters with a single Criteria-based method.
🔹 Key benefit:
You avoid:
❌ Writing dozens of HQL/SQL variants manually.
✅ Instead, you dynamically build exactly the query needed at runtime, depending on available inputs.
✅ Key takeaway:
Changing Criteria API at runtime means conditionally adding or modifying query parts on the fly, letting you handle flexible, user-driven searches or reports with a single, maintainable query builder.