0
我試圖用子查詢和IN表達式多次編寫查詢語句。但我從來沒有成功過。JPA 2.0,Criteria API,子查詢,in子查詢
在JPA中構建查詢後,我總是得到不正確的結果。我下面的SQL請求:
SELECT distinct
ss.*
FROM
table1 ss
where
ss.active=1
and
ss.id not in (select ia.organization_id from table2 ia where ia.is_allow = 'Y')
我的代碼使用標準如下API:
CriteriaQuery<Table1> cq = qb.createQuery(Table1.class);
Root<Table1> table = cq.from(Table1.class);
cq.select(table);
List<Predicate> predicateList = new ArrayList<Predicate>();
Subquery<Table1> subquery = cq.subquery(Table1.class);
Root<Table2> subroot = subquery.from(Table2.class);
subquery.select(subroot.get(Table2_.table1));
subquery.where(qb.equal(subroot.get(Table2_.isAllow.getName()), Boolean.TRUE));
predicateList.add(qb.not(qb.in(table.get(Table1_.id.getName())).value(subquery)));
if (!predicateList.isEmpty()) {
Predicate[] array = new Predicate[predicateList.size()];
cq.where(qb.and(predicateList.toArray(array)));
}
cq.distinct(true);
TypedQuery<Table1> qry = entityManager.createQuery(cq);
return qry.getResultList();
在此之後,我得到遵循SQL請求:
SELECT DISTINCT t0.*
FROM TABLE1 t0
WHERE (t0.ACTIVE = 1 AND NOT (t0.ID IN (SELECT 1 FROM TABLE2 t2, TABLE1 t1 WHERE ((t2.IS_ALLOW = 'Y')
AND (t1.ID = t2.ORGANIZATION_ID)))))
爲什麼在這段代碼「SELECT 1 FROM TABLE2 t2,TABLE1 t1「等等....我在這個t1.id中等待。
你能幫我嗎?