2014-01-28 53 views
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中等待。

你能幫我嗎?

回答

0

如果子查詢返回公正和整數

select ia.organization_id from table2 ia where ia.is_allow = 'Y' 

嘗試。

Subquery<Integer> subquery = cq.subquery(Integer.class); 
Root<Table2> subroot = subquery.from(Table2.class); 
subquery.select(subroot.get("organization_id")); 
subquery.where(qb.equal(subroot.get("is_allow"), Boolean.TRUE)); 

上面的子查詢應返回將放置在IN語句中的整數。

然後你的邏輯可以適用。

CriteriaQuery<Table1> cq = qb.createQuery(Table1.class); 
Root<Table1> table = cq.from(Table1.class); 
cq.select(table); 
cq.distinct(true) 
    .where(qb.not(qb.in(root.get("get")).value(subquery)) 
    .and(cb<Integer>equals(root.get("active"),1)) 

不知道這是否可行。 TypedQuery qry = entityManager.createQuery(cq); 如果cq「Criteria Query」是Table1.class的類型,那麼TypedQuery將是 更改爲

TypedQuery<Table1> qry = entityManager.createQuery(cq);