2010-09-18 51 views
0

我堅持一個非常簡單的條件查詢的問題:Hibernate的簡單條件查詢解決問題

sess .createCriteria(user.class, "user") 
     .user_c.add(Restrictions.eq("user.status", 1)) 
     .user_c.createAlias("user.userCategories","ucs") 
     .add(Restrictions.eq("ucs.category_id",1)); 
     .add(Restrictions.eq("ucs.category_id",'yes')); 
     .add(Restrictions.eq("ucs.category_id",2)); 
     .add(Restrictions.eq("ucs.category_id",'no')).list(); 

當然,這導致沒有用戶。

在SQL

我也試了一下:

Select * FROM users user , ec_user_category uc where 
    uc.user_login = user.login AND 
    uc.status = 1 AND 
    ((uc.category_id = 1 AND uc.value = 'yes') AND (uc.category_id = 2 AND uc.value = 'no')) 

也沒有,當然用戶在SQL

兩種解決方案,不是很有效,我認爲:

Select a.login from 
     (Select user.login , COUNT(*) as counter FROM users user , ec_user_category uc 
     where user.status = 1 
     and uc.user_login = user.login 
     and 
      ((uc.category_id = 1 and uc.value = 'yes') 

      OR (uc.category_id = 2 and uc.value = 'no')) 

     GROUP BY user.login) a where a.counter = 2 

其他:

Select * FROM users u 
    JOIN user_category uc on uc.user_login = u.login 
    JOIN user_category uc2 on uc2.user_login = u.login 
WHERE (uc.category_id = 1 and uc.value = 'yes') 
     AND (uc2.category_id = 2 and uc2.value = 'no') 

這些r結果給了我很好的信息,但我不認爲這是正確的方式。我將如何使用Criteria API在Hibernate中實現這一點。

或者需要我在我的數據庫中的新表?

回答