メインクエリとサブクエリで 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)