Hibernate在子查询中的位置

时间:2012-04-08 21:30:39

标签: java hibernate

我有一张表:

Users (user_id, name, age, country_id)

现在我想要一个类似的查询:

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

用户没有任何关系,我只想在没有任何关联的情况下这样做。

我想用Criteria查询来做这件事。

我看到了限制,但不确定它是否有where in子句:

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

所以我的更改是我有一份国家ID列表(List countryIds),我需要通过。

3 个答案:

答案 0 :(得分:3)

你想要'country_id in(...)'吗?

如果是,那么:

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

我还使用了“countryId” - 在标准中使用属性名称,而不是表格列名。

答案 1 :(得分: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); 

答案 2 :(得分:0)

Eugene的解决方案是最好的解决方案。如果要匹配多个可能的国家/地区ID,请使用Restrictions.in。

您也可以在(...)中使用Property.forName(...)。,例如:

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