简体   繁体   English

如何在JPQL中获得所有实体但已过滤的关系

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

I have a OneToMany relation between to entities: Area and Reservation. 我与实体之间存在一个OneToMany关系:区域和预订。 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 . 这是因为您的查询具有Where子句,该子句不会返回Area中存在但Reservation中没有的记录。

Here you want something that possibly JPA doesn't support an ON clause instead of Where . 在这里,您想要的是JPA可能不支持ON子句的地方,而不是Where

JPA JPQL does not support arbitrary relationships between object being defined in the "on" clause JPA JPQL不支持在“ on”子句中定义的对象之间的任意关系

So what could be the solution for this: 那么这可能是解决方案:

Using SQL Query instead of JPQL . 使用SQL Query代替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. 不能部分填充@OneToMany集合。 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. 这样,您只有预订区域可以满足您的需求,尽管有不同的区域。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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