简体   繁体   中英

How to get all of one entity but filtered relation in JPQL

I have a OneToMany relation between to entities: Area and Reservation. Area has many reservations (or none) and Reservation has one Area. I would like to query all Area's but for each area, I would only have the Reservations which fullfill a condition.

So far I've tried something like this:

em.createQuery("SELECT DISTINCT a FROM Area a LEFT JOIN a.reservations r WHERE r.startDate < :fromDate")
                .setParameter("fromDate", fromDate, TemporalType.TIMESTAMP)
                .getResultList();

But then it will not return those Areas which does not have any Reservations that fullfill the condition.

This is because your query has a Where clause, that doesn't return the records which is present in Area but not in Reservation .

Here you want something that possibly JPA doesn't support an ON clause instead of Where .

JPA JPQL does not support arbitrary relationships between object being defined in the "on" clause

So what could be the solution for this:

Using SQL Query instead of JPQL .

Try something using below based on your objects tables and field value:

em.createSQLQuery("SELECT DISTINCT a.area_name FROM area a LEFT JOIN a.reservations r ON r.start_date< :fromDate")
                .setParameter("fromDate", fromDate, TemporalType.TIMESTAMP)
                .getResultList();

You cant populate a @OneToMany collection partially. Since you have a bi-direcational relationship, you could query the entities the other way round from Reservations:

SELECT r FROM Reservation r WHERE r r.startDate < :fromDate

This way you have only the Reservations which fullfill your requirement albeit with non distinct Areas.

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