2012-12-13 56 views
9

我有兩個表,分別命名爲table1,table2.兩個表都具有相同的no域。這兩個表之間沒有關係。我的要求是我希望所有記錄在table1中沒有在table2中。所以我寫了一個使用Criteria API的查詢。但它沒有給出正確的結果。由於我對這個JPA和標準API不熟悉,任何人都可以指出我在哪裏做錯了。我正在使用下面的代碼來執行此操作。在jpa標準api中使用NOT EXISTS構建查詢

CriteriaBuilder cb = mediationEntityManager.getCriteriaBuilder(); 
CriteriaQuery<Table1> cq = cb.createQuery(Table1.class); 
Root<Table1> table1 = cq.from(Table1.class); 
cq.select(table1) 

Subquery<Table2> subquery = cq.subquery(Table2.class) 
Root table2 = subquery.from(Table2.class) 
subquery.select(table2) 
cq.where(cb.not(cb.exists(subquery))) 
TypedQuery<Table1> typedQuery = mediationEntityManager.createQuery(cq); 
List<Table1> resultList = typedQuery.getResultList(); 

MySQL查詢:

SELECT table1 
FROM table1 table1 
WHERE NOT EXISTS (SELECT table2 
        FROM table2 table2 
        WHERE table2.name = table1.name 
          AND table2.education = table1.education 
          AND table2.age = table1.age) 
     AND table1.name = 'san' 
     AND table1.age = '10'; 

我需要爲上述MySQL查詢的JPA標準API查詢。

+0

但你是如何區分這些表之間的數據,指定標準/柱等 –

+0

嗨非常感謝給我給我原來的實際MySQL查詢Question.Plz查看一下,如果可能的話給出答覆我的Jpa標準API查詢相同的MySQL查詢。 – aaaa

回答

12

您可以使用Criteria API嘗試下面的代碼。我沒有嘗試,但你可以嘗試修改相應的代碼。

CriteriaBuilder cb = mediationEntityManager.getCriteriaBuilder(); 
CriteriaQuery<Table1> query = cb.createQuery(Table1.class); 
Root<Table1> table1 = query.from(Table1.class); 
query.select(table1); 
//-- 
Subquery<Table2> subquery = query.subquery(Table2.class); 
Root<Table2> table2 = subquery.from(Table2.class); 
subquery.select(table2); 
//-- 
List<Predicate> subQueryPredicates = new ArrayList<Predicate>(); 
subQueryPredicates.add(cb.equal(table1.get(Table1_.name), table2.get(Table2_.name))); 
subQueryPredicates.add(cb.equal(table1.get(Table1_.age), table2.get(Table2_.age))); 
subQueryPredicates.add(cb.equal(table1.get(Table1_.education), table2.get(Table2_.education))); 
subquery.where(subQueryPredicates.toArray(new Predicate[]{})); 
//-- 
List<Predicate> mainQueryPredicates = new ArrayList<Predicate>(); 
mainQueryPredicates.add(cb.equal(table1.get(Table1_.name), "san"); 
mainQueryPredicates.add(cb.equal(table1.get(Table1_.age), "10"); 
mainQueryPredicates.add(cb.not(cb.exists(subquery))); 
//-- 
query.where(mainQueryPredicates.toArray(new Predicate[]{})); 
TypedQuery<Table1> typedQuery = mediationEntityManager.createQuery(query); 
List<Table1> resultList = typedQuery.getResultList(); 

此外,您還可以試試下面JPQL查詢,這是比較容易理解,改變&調試。

SELECT t1 
FROM table1 t1, 
     table2 t2 
WHERE t1.name = 'san' 
     AND t1.age = '10' 
     AND (t2.name <> t1.name 
      AND t2.education <> t1.education 
      AND t2.age <> t1.age); 
+0

嘿,非常感謝......它工作正常。 – aaaa

+0

@aaaa歡迎您採用哪種方式 –

+0

我首選標準Api bcoz是我的要求。 – aaaa