JPA中何时使用实体类型Path而非Join?附规范示例疑问
Great question—let’s unpack this clearly, since understanding when to use Path vs Join is key to writing clean Criteria API code.
When to use a Path instead of an explicit Join?
Use a Path (the chained get() calls) when you only need to navigate an association once for a condition or projection, and you don’t need to reuse that association reference elsewhere in your query. It’s more concise for one-off access.
Explicit Join shines when:
- You need to reuse the association multiple times (e.g., filter on both an order’s status and its product’s category)
- You want to specify a join type (like
LEFT JOINinstead of the defaultINNER JOIN) - You need to add a custom
ONclause to the join
How to access Product (Book) name without using Join in your example?
You can just chain the get() calls directly from the Root<Customer>, combined with cb.treat() for the downcast to Book. Here’s what that looks like:
CriteriaQuery<Customer> q = cb.createQuery(Customer.class); Root<Customer> customer = q.from(Customer.class); q.where(cb.equal( cb.treat(customer.get(Customer_.orders).get(Order_.product), Book.class) .get(Book_.name), "Iliad" )); q.select(customer);
This works because each get() call navigates the association path: customer → orders → product, then treat() casts the Product to Book so you can access the name attribute specific to Book.
Does this path navigation translate to SQL joins?
Absolutely! Whether you use an explicit Join or implicit Path navigation, JPA will generate the necessary SQL JOIN clauses under the hood. The example above will produce the same joins (Customer ↔ Order, Order ↔ Book) as the original code with the explicit Join—the only difference is that in the Criteria API, you don’t have a named reference to the Order association.
内容的提问来源于stack exchange,提问作者eastwater

