JPA not in subqueries CriteriaBuilder

   

 

Writing Strongly Typed NOT IN Subqueries with JPA CriteriaBuilder

Written by Sean Ryan on May 9, 2012. Posted in Misc Ramblings

This one took a while to figure out and it required a few beers.

Let’s say you have an entity called Product and an entity called ProductOwner and there is a 1 to n relationship from ProductOwner to Product but you can only access Product from ProductOwner.

This may not be the way the database is designed – that would be terrible, but it may be the way your model has been designed. Probably an oversight but in any case, now you’re stuck with it.

What do you do if you want find out how many ProductOwners don’t actually own any products? It can happen, but because of the design of the model, it’s not obvious how to fetch those records.

In SQL, it’s easy…

select * from ProductOwner po where po.id not in (select p.id from product)

Using JPA CriteriaBuilder you would do the following.

CriteriaBuilder cb = entityManager.getCriteriaBuilder();
CriteriaQuery<ProductOwner> query = cb.createQuery(ProductOwner.class);
Root<ProductOwner> poRoot = query.from(ProductOwner.class);
query.select(poRoot);

Subquery<Product> subquery = query.subquery(Product.class);
Root<Product> subRoot = subquery.from(Product.class);
subquery.select(subRoot);

Predicate p = cb.equal(subRoot.get(Product_.productOwner),poRoot);
subquery.where(p);
query.where(cb.not(cb.exists(subquery))); 

TypedQuery<ProductOwner> typedQuery = entityManager.createQuery(query);

List<ProductOwner> result = typedQuery.getResultList();
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值