Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JPQL query with WHERE on nested fields

I have a java entity class UserBean with a list of events:

@OneToMany
private List<EventBean> events;

EventBean has Date variable:

@Temporal(javax.persistence.TemporalType.TIMESTAMP)
private Date eventDate;

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.

By the way, I use EclipseLink version 2.5.0.v20130507-3faac2b.

What can I do to make this query work? Thanks.

like image 670
user473453 Avatar asked Sep 09 '13 19:09

user473453


People also ask

Can we use subquery in JPQL?

A subselect is a query embedded into another query. It's a powerful feature you probably know from SQL. Unfortunately, JPQL supports it only in the WHERE clause and not in the SELECT or FROM clause. Subqueries can return one or multiple records and can use the aliases defined in the outer query.

Can we use inner join in JPQL?

In JPQL, JOIN can only appear in a FROM clause. The INNER keyword is optional (i.e. INNER JOIN is equivalent to JOIN).

Which of the following methods is used to execute a select JPQL query?

Query createQuery(String name) - The createQuery() method of EntityManager interface is used to create an instance of Query interface for executing JPQL statement.

Which of the following is JPQL aggregate function?

JPQL supports the five aggregate functions of SQL: COUNT - returns a long value representing the number of elements. SUM - returns the sum of numeric values. AVG - returns the average of numeric values as a double value.


1 Answers

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:

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.

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
like image 162
Mikko Maunu Avatar answered Nov 13 '22 08:11

Mikko Maunu