2012-04-08 122 views
0

我有這樣一個表:休眠其中子查詢

Users (user_id, name, age, country_id) 

現在我要像一個查詢:

SELECT * 
FROM users 
where country_id in (1,2,3,4,5) 

有用戶沒有關係,我只是想做到這一點不任何關聯。

我想用Criteria查詢來做到這一點。

我看到的限制,但不知道是否有條款A,其中:

sessionFactory.getCurrentSession().createCriteria(User.class) 
    .add(Restrictions.eq("country_id", countryId) 
    .list(); 

所以我的變化是,我有國家IDS(名單countryIds),我需要傳遞的列表。

回答

3

你想'country_id in(...)'嗎?

如果是的話:

sessionFactory.getCurrentSession().createCriteria(User.class) 
.add(Restrictions.in("countryId", countryIds) 
.list(); 

此外,我用「countryId」 - 在您使用屬性名稱,而不是表的列名的標準。

+0

,爲您免除get前綴嗎?像getCountryId你使用私有變量? – Blankman 2012-04-08 22:49:42

+0

對,你使用屬性名稱,而不是getter名稱。 – 2012-04-09 00:51:14

1
List<Integer> countryIds=//get data from either a query or criteria 

Criteria c = // obtain criteria from session 

Disjunction disJunction = Restrctions.disjunction(); 
disJunction .add(Restrictions.in("country_id", countryIds)); 
c.add(disJunction); 
0

尤金的解決方案是一個去與。如果您想匹配多個可能的國家/地區ID,則可以使用Restrictions.in。

您也可以使用Property.forName(...)在(...),如:當您使用屬性

sessionFactory.getCurrentSession().createCriteria(User.class) 
    .add(Property.forName("countryId").in(countryIds)) 
    .list();