2012-04-08 136 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();