JPA Criteria API是否支持实体类型表达式?JPQL已有对应示例
Absolutely! The JPA Criteria API fully supports entity type expressions, just like the JPQL snippet you provided (SELECT e FROM Employee e WHERE TYPE(e) IN (Exempt, Contractor)). Here's how to replicate that logic using the Criteria API:
Step-by-Step Implementation
Let’s assume Employee is your base entity class, with Exempt and Contractor as its subclasses (works with any JPA inheritance strategy like SINGLE_TABLE, JOINED, or TABLE_PER_CLASS):
Set up your CriteriaBuilder and CriteriaQuery:
CriteriaBuilder cb = entityManager.getCriteriaBuilder(); CriteriaQuery<Employee> query = cb.createQuery(Employee.class); Root<Employee> employeeRoot = query.from(Employee.class);Build the type filter condition:
Usecb.type(employeeRoot)to get an expression representing the entity's runtime type, then chainin()to match multiple subclass types:query.select(employeeRoot) .where(cb.in(cb.type(employeeRoot)) .value(Exempt.class) .value(Contractor.class));Execute the query:
List<Employee> filteredEmployees = entityManager.createQuery(query).getResultList();
Bonus: Matching a Single Subclass Type
If you only need to filter for one specific subclass, you can use cb.equal() instead of in():
query.where(cb.equal(cb.type(employeeRoot), Contractor.class));
This feature is incredibly useful when working with inherited entity hierarchies, letting you precisely target specific subclasses without messy manual filters.
内容的提问来源于stack exchange,提问作者eastwater

