使用Vararg方法进行Hibernate Criteria查询

时间:2015-09-21 09:41:50

标签: java hibernate java-ee

目标是获得具有特定ID的某些实体。我想创建一个vararg方法,它将获取实体ID并根据id返回实体列表:

@Override
public List<Entity> getEntities(long... ids) {

    Session s = sessionFactory.getCurrentSession();
    s.beginTransaction();
    Criteria criteria = s.createCriteria(Entity.class);

    for (long id : ids) {
        // for very id I want to create a Restriction 
        // but Restriction goes like
        //  criteria.add(Restrictions.or(Restrictions.eq("id", id),Restrictions.eq("id", id)));
    }

    s.getTransaction().commit();
    return null;
}

用法将是:

List<Entity> list = getEntities(453,282,781,784);

如何创建此类条件查询?

2 个答案:

答案 0 :(得分:2)

可变数量的OR id = ?子句就像一个IN子句。这是使用Restrictions.in方法完成的:

criteria.add(Restrictions.in("id", ids));

答案 1 :(得分:0)

criteria.add(Restrictions.in("id", ids));
criteria.addOrder(Order.asc("id"));

将解决您的问题,它将按照您传递给varargs的相同顺序返回结果