JPA Criteria API

 Here’s an example of how to use the JPA Criteria API, which is the modern replacement for Hibernate Criteria API. The JPA Criteria API is type-safe, object-oriented, and works seamlessly with JPA.


Step 1: Entity Class

We’ll use the Employee entity:

import jakarta.persistence.*; @Entity @Table(name = "employee") public class Employee { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private int id; @Column(name = "name") private String name; @Column(name = "department") private String department; @Column(name = "salary") private double salary; // Getters and setters public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getDepartment() { return department; } public void setDepartment(String department) { this.department = department; } public double getSalary() { return salary; } public void setSalary(double salary) { this.salary = salary; } }

Step 2: JPA Criteria Query Examples

Example 1: Fetch All Employees

import jakarta.persistence.*; import jakarta.persistence.criteria.*; import java.util.List; public class JPACriteriaExample { public static void main(String[] args) { EntityManagerFactory emf = Persistence.createEntityManagerFactory("your-persistence-unit"); EntityManager em = emf.createEntityManager(); EntityTransaction transaction = em.getTransaction(); try { transaction.begin(); // Create CriteriaBuilder CriteriaBuilder cb = em.getCriteriaBuilder(); // Create CriteriaQuery CriteriaQuery<Employee> query = cb.createQuery(Employee.class); // Define root for the query Root<Employee> root = query.from(Employee.class); // Select all query.select(root); // Execute query List<Employee> employees = em.createQuery(query).getResultList(); for (Employee emp : employees) { System.out.println("ID: " + emp.getId() + ", Name: " + emp.getName() + ", Department: " + emp.getDepartment() + ", Salary: " + emp.getSalary()); } transaction.commit(); } catch (Exception e) { if (transaction != null) transaction.rollback(); e.printStackTrace(); } finally { em.close(); emf.close(); } } }

Example 2: Fetch Employees with Salary Greater than a Threshold

CriteriaBuilder cb = em.getCriteriaBuilder(); CriteriaQuery<Employee> query = cb.createQuery(Employee.class); Root<Employee> root = query.from(Employee.class); // Add condition query.select(root).where(cb.gt(root.get("salary"), 50000.0)); List<Employee> employees = em.createQuery(query).getResultList();

Example 3: Fetch Employees from a Specific Department

query.select(root).where(cb.equal(root.get("department"), "HR")); List<Employee> employees = em.createQuery(query).getResultList();

Example 4: Fetch Employees with Multiple Conditions

query.select(root).where( cb.and( cb.equal(root.get("department"), "IT"), cb.gt(root.get("salary"), 60000.0) ) ); List<Employee> employees = em.createQuery(query).getResultList();

Example 5: Sort Results

query.select(root) .orderBy(cb.asc(root.get("name"))); // Sort by name ascending List<Employee> employees = em.createQuery(query).getResultList();

Example 6: Pagination

TypedQuery<Employee> typedQuery = em.createQuery(query); typedQuery.setFirstResult(0); // Start position typedQuery.setMaxResults(10); // Max results List<Employee> employees = typedQuery.getResultList();

Advantages of JPA Criteria API

  1. Type-Safe: Eliminates the risk of runtime errors caused by typos in queries.
  2. Dynamic Query Building: Perfect for complex, dynamic queries.
  3. Standardized: Works with any JPA-compliant provider (e.g., Hibernate, EclipseLink).

Comments