2012-05-14 58 views
3

我在學習jpa-hibernate基礎知識。簡單的JPA 2條件查詢「where」條件

我有這個疑問的讓所有用戶:

CriteriaBuilder cb = getEntityManager().getCriteriaBuilder(); 
     CriteriaQuery cq = cb.createQuery(); 
     cq.select(cq.from(Utente.class)); 
     return getEntityManager().createQuery(cq).getResultList(); 

現在我想通過一個名爲「鬼」地方等於真(或假,這取決於)一個布爾字段進行過濾。

翻譯:

SELECT * FROM用戶WHERE鬼= 0;

我必須使用cq.where()嗎?怎麼樣?

回答

6

是的,你必須使用cq.where()

嘗試這樣:

Root<Utente> utente = cq.from(Utente.class); 
boolean myCondition = true; // or false 
Predicate predicate = cb.equal(utente.get(Utente_.ghost), myCondition); 
cq.where(predicate); 

當我使用應自動生成規範元模型類Utente_。這避免了在輸入字段名稱時出錯的風險,並且增強了類型安全性。否則,你可以使用

Predicate predicate = cb.equal(utente.get("ghost"), myCondition); 
+0

沒關係,但用cq.select(utente)編輯你的答案; –