JPA Path Expression, operator IN and Collection properties

If we want to select the Orders whose price is greate than 100, we can use this JPQL query:

 

select o from Order o where o.price > 100

Here "o.price" is used to refer to the property "price" of JPA entity "Order". This expression is called "Path Expression". The path expression is an identfier variable "o" followed by the navigation operator "." and then a property or an associated property.

 

Problem is that the path expression cannot evaluate/apply to a collection. For example, if entity "Order" has a memeber of "Collection<Item> items", which maps to the items in the order, then "o.items.price" is illegal. This is because navigation to items results in a Collection, not a single Item.

 

To handle this situation, an identifier variable may be declared in the FROM clause to range over the elements of the "items" collection:

SELECT i.name
FROM Order o, IN(o.items) i
where i.price > 100

 The above query would return the item names whose price is greater than 100. It does that by searching the "items" collection of the Order entity.

 

The argument to the "IN" operator must be a collection-valued path expression., which specifies a navigation to a collection-valued association property of an entity or embedded class. The identifier "i" in the above example designates a member in the property "Collection<Item> items".

 

The above query can be better written as a JOIN statement, which is easier to understand:

SELECT i.name
FROM Order o JOIN o.items i
WHERE i.price > 100

 

For an association or collection property of java.util.Map, the identification variable (eg, "i") refers to an element of the map value. Functions KEY, VALUE and ENTRY may be used to refer to the map key, value and entry, repectively. As this example shows:

SELECT VALUE(o)
FROM Customer AS c JOIN c.orders AS o
WHERE KEY(o) >= 2 

 Here the path expression KEY(o) and VALUE(o) are the map key and map value of the orders map of the customer, respectively. The keyword VALUE is optional here, thus VALUE(o) and o are equivalent in this query.

 

Warning: queries not tested and modified from the reference just in order to illustrate the concepts.

 

Reference:

"Java Persistence with JPA" - by Mr. Daoqi Yang

 

你可能感兴趣的:(jpa,Path Expression)