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中等待。
你能帮我吗?