我在主查询和子查询中明确定义了一个 WHERE 语句。如果我省略了子查询,这将打印在 JPA 日志中。但是,如果我添加子查询,则不会应用相同的 where 子句。省略 WHERE 子句(选择 σ)的 JPA Criteria 查询是什么?
// 1) MainQuery
// Create the FROM
Root<PubThread> rootPubThread = cq.from(PubThread.class);
// Create the JOIN fro the first select: join-chaining. You only need the return for ordering. e.g. cq.orderBy(cb.asc(categoryJoin.get(Pub_.title)));
Join<Pub, PubCategory> categoryJoin = rootPubThread.join(PubThread_.pups).join(Pub_.pubCategory);
// Create the WHERE
cq.where(criteriaBuilder.not(criteriaBuilder.equal(rootPubThread.get(PubThread_.id), threadId)));
// Create the SELECT, at last
cq.select(rootPubThread).distinct(true);
// 2) Subquery
Subquery<PubThread> subquery = cq.subquery(PubThread.class);
Root<PubThread> rootPubThreadSub = subquery.from(PubThread.class);
subquery.where(criteriaBuilder.equal(rootPubThread.get(PubThread_.id), threadId));
Join<Pub, PubCategory> categoryJoinSub = rootPubThreadSub.join(PubThread_.pups).join(Pub_.pubCategory);
subquery.select(rootPubThreadSub);
Predicate correlatePredicate = criteriaBuilder.equal(rootPubThreadSub.get(PubThread_.id), rootPubThread);
subquery.where(correlatePredicate);
cq.where(criteriaBuilder.exists(subquery));
这是此查询的输出:
select distinct
pubthread0_.id as id3_,
pubthread0_.dateCreated as dateCrea2_3_,
pubthread0_.dateModified as dateModi3_3_,
pubthread0_.name as name3_
from
pubthread pubthread0_
inner join
pub_pubthread pups1_ ON pubthread0_.id = pups1_.pubThreads_id
inner join
pub pub2_ ON pups1_.pups_id = pub2_.id
inner join
PubCategory pubcategor3_ ON pub2_.pubCategoryId = pubcategor3_.id
where
exists( select
pubthread4_.id
from
pubthread pubthread4_
inner join
pub_pubthread pups5_ ON pubthread4_.id = pups5_.pubThreads_id
inner join
pub pub6_ ON pups5_.pups_id = pub6_.id
inner join
PubCategory pubcategor7_ ON pub6_.pubCategoryId = pubcategor7_.id
where
pubthread4_.id=pubthread0_.id)