JPA Path Expression, operator IN and Collection properties

10 篇文章 0 订阅

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

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值