Java.Hibernate.Beginner.What is the Criteria API in Hibernate?

The Criteria API in Hibernate is an object-oriented, programmatic way to build dynamic queries — instead of writing HQL or SQL strings manually, you construct queries using Java objects and method calls.

🔹 Why use Criteria API?
✅ Useful when you need to build dynamic queries at runtime, where conditions, joins, or projections depend on user input or other variables.
✅ Provides type safety — you avoid typos in HQL/SQL strings because the compiler checks your Java code.
✅ Easier to read and maintain for complex or dynamic queries.

🔹 How does it work?

  • Hibernate offers two types of Criteria APIs:
    • Legacy Criteria API (Criteria class in Hibernate 5 and earlier) — considered deprecated.
    • JPA Criteria API (CriteriaBuilder, CriteriaQuery) — standard in JPA 2.0+ and recommended today.

🔹 Basic example using JPA Criteria API:

Session session = sessionFactory.openSession();
CriteriaBuilder cb = session.getCriteriaBuilder();

CriteriaQuery<User> cq = cb.createQuery(User.class);
Root<User> root = cq.from(User.class);

// Add where clause: username = "alice"
cq.select(root).where(cb.equal(root.get("username"), "alice"));

User user = session.createQuery(cq).uniqueResult();

if (user != null) {
    System.out.println("Found user: " + user.getUsername());
}

session.close();

✅ Here:

  • CriteriaBuilder creates a type-safe query plan.
  • CriteriaQuery represents the query.
  • Root<User> defines the entity to query.
  • cb.equal(...) builds conditions dynamically.

🔹 Benefits of Criteria API:
✅ Fully dynamic → you can add conditions, joins, orderings at runtime.
Type-safe → compiler catches mistakes with field names or types.
✅ Standard JPA API → works across all JPA providers, not just Hibernate.

🔹 Use case examples:

  • Building advanced search screens with many optional filters.
  • Generating reports with different filters, sorting, and grouping options.
  • Creating reusable query builders in your data access layer.

Key takeaway:
The Criteria API lets you build dynamic, type-safe queries using Java objects, making it ideal for complex or runtime-generated queries — and it avoids fragile HQL or SQL string concatenation.

This entry was posted in Без рубрики. Bookmark the permalink.