在嵌套字段上使用WHERE进行JPQL查询 [英] JPQL query with WHERE on nested fields
问题描述
我有一个带有事件列表的Java实体类UserBean:
I have a java entity class UserBean with a list of events:
@OneToMany
private List<EventBean> events;
EventBean具有Date变量:
EventBean has Date variable:
@Temporal(javax.persistence.TemporalType.TIMESTAMP)
private Date eventDate;
现在在UserBean中,我想创建一个NamedQuery,它返回特定范围内的所有日期:
Now in UserBean I want to create a NamedQuery that returns all dates that fall within a specific range:
@NamedQuery(name="User.findEventsWithinDates",
query="SELECT u.events FROM UserBean u WHERE u.name = :name AND u.events.eventDate > :startDate AND u.events.eventDate < :endDate")
上面的查询虽然不能编译.我收到此错误:
The above query does not compile though. I get this error:
The state field path 'u.events.eventDate' cannot be resolved to a valid type.
顺便说一下,我使用的是EclipseLink 2.5.0.v20130507-3faac2b版本.
By the way, I use EclipseLink version 2.5.0.v20130507-3faac2b.
我该怎么做才能使此查询正常工作?谢谢.
What can I do to make this query work? Thanks.
推荐答案
路径u.events.eventDate
在JPQL中是非法构造,因为不允许它通过集合值的路径表达式进行导航.在这种情况下,u.events
是一个集合值的路径表达式.在JPA 2.0规范中,这是用以下单词来表示的:
Path u.events.eventDate
is an illegal construct in JPQL, because it is not allowed to navigate via a collection valued path expression. In this case u.events
is a collection valued path expression. In JPA 2.0 specification this is told with following words:
从路径组成路径表达式在语法上是非法的 计算结果为集合的表达式.例如,如果o 指定Order,路径表达式o.lineItems.product不合法 因为导航到lineItems会生成一个集合.这个案例 验证查询字符串时,应该会产生错误.处理 这样的导航,必须在 FROM子句可覆盖lineItems集合的元素.
It is syntactically illegal to compose a path expression from a path expression that evaluates to a collection. For example, if o designates Order, the path expression o.lineItems.product is illegal since navigation to lineItems results in a collection. This case should produce an error when the query string is verified. To handle such a navigation, an identification variable must be declared in the FROM clause to range over the elements of the lineItems collection.
可以通过使用JOIN解决此问题:
This problem can be solved by using JOIN:
SELECT distinct(u)
FROM UserBean u JOIN u.events e
WHERE u.name = :someName
AND e.eventDate > :startDate
AND e.eventDate < :endDate
这篇关于在嵌套字段上使用WHERE进行JPQL查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!