You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

JPA Criteria API是否支持实体类型表达式?JPQL已有对应示例

JPA Criteria API Support for Entity Type Expressions

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):

  1. Set up your CriteriaBuilder and CriteriaQuery:

    CriteriaBuilder cb = entityManager.getCriteriaBuilder();
    CriteriaQuery<Employee> query = cb.createQuery(Employee.class);
    Root<Employee> employeeRoot = query.from(Employee.class);
    
  2. Build the type filter condition:
    Use cb.type(employeeRoot) to get an expression representing the entity's runtime type, then chain in() to match multiple subclass types:

    query.select(employeeRoot)
         .where(cb.in(cb.type(employeeRoot))
             .value(Exempt.class)
             .value(Contractor.class));
    
  3. 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.27 03:29:04