简体   繁体   中英

JPA Criteria select with two subqueries / joins

I'm fighting this whole day and I can't figure it out. I'm JPA beginner, so for now Criteria API is a nightmare for me. The problem:

I have 3 entities: Policy, Customer, Insurer . Policy has references to a Customer and an Insurer (eager fetch here). Customer has list of policies, so do Insurer (lazy fetch here).

I'm trying to find all policies in a way described below (SQL):


SELECT * FROM POLICY as p WHERE
p.CUSTOMER_ID IN (SELECT ID FROM CUSTOMER as c WHERE [customerPredicates])
AND
p.INSURER_ID IN (SELECT ID FROM INSURER as i WHERE [insurerPredicates])
AND
[policyPredicates]

Where CUSTOMER_ID / INSURER_ID are JoinColumns generated from @ManyToOne relationships in Policy.

customerPredicates / insurerPredicates / policyPredicates are lists of predicates ('where' conditions prepared from given search criteria).

How can I achieve that in Criteria API? What are rules / good practices for creating this kind of queries?

Try to rewrite the SQL first to use JOINS

SELECT * 
FROM POLICY as p 
     INNER JOIN CUSTOMER as c ON p.CUSTOMER_ID = c.ID
     INNER JOIN INSURER as i ON p.INSURER_ID = i.ID
WHERE [customerPredicates])
AND
[insurerPredicates])
AND
[policyPredicates]

The all you need is criteria api is to get main criteria (for the Policy entity) and create aliases for Customer entity and Insurer entity.

    Criteria criteria = session.createCriteria(Policy.class, "p");
    criteria.setFetchMode("p.Customer", FetchMode.JOIN);
    criteria.createAlias("p.Customer", "c");

and add your restriction to the "c" alias for Customer.

And the same for Insurer

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM