Hibernate Criteria AND OR操作在多个地方

时间:2014-05-12 08:26:48

标签: java hibernate

我正在尝试使用Hibernate Criteria进行以下查询

SELECT * FROM EUser
WHERE 
userName LIKE '%mat%' OR
firstName LIKE '%mat%' OR
lastName LIKE '%mat%' OR
middleName LIKE '%mat%' AND 
enable = 'ACTIVE';

现在我可以使用如下的查询(//通过googling找到)

Criteria criteria = session.createCriteria(EUser.class);
        Criterion roll = Restrictions.eq("rollNo", 2);
        Criterion name = Restrictions.eq("name", "John");
        LogicalExpression expression = Restrictions.or(roll, name);
        criteria.add(expression);
        List list = criteria.list();

Criteria criteria = session.createCriteria(EUser.class);
        Criterion roll = Restrictions.eq("rollNo", 1);
        Criterion name = Restrictions.eq("name", "John");
        LogicalExpression expression = Restrictions.and(roll, name);
        criteria.add(expression);
        List list = criteria.list();

但是对于如此少的查询似乎编码太多了

有没有更简单的代码来实现这个目标?

2 个答案:

答案 0 :(得分:5)

这是您的实际查询,稍微简洁一点。

   session.createCriteria(EUser.class)
   .add(Restrictions.disjunction()
      .add(Restrictions.like("userName", "mat%"))
      .add(Restrictions.like("firstName", "mat%")) 
      .add(Restrictions.like("lastName", "mat%")) 
      .add(Restrictions.like("middleName", "mat%")))
   .add(Restrictions.eq("enable ", "active"))
   .list();

相当罗嗦,但确保您的代码不错,并且易于进行动态和通用查询。

答案 1 :(得分:0)

对于Hibernate 5.2版本以后的新条件:

CriteriaBuilder criteriaBuilder = getSession().getCriteriaBuilder();
CriteriaQuery<EUser> criteriaQuery = criteriaBuilder.createQuery(EUser.class);

Root<EUser> root = getRoot(criteriaQuery);
Path<String> userName = root.get("userName");
Path<String> firstName = root.get("firstName");
Path<String> lastName = root.get("lastName");
Path<String> middleName = root.get("middleName");
Path<String> enable = root.get("enable");

Predicate userNamePredicate = criteriaBuilder.like(userName, "%mat%");
Predicate firstNamePredicate = criteriaBuilder.like(firstName, "%mat%");
Predicate lastNamePredicate = criteriaBuilder.like(lastName, "%mat%");
Predicate middleNamePredicate = criteriaBuilder.like(middleName, "%mat%");
Predicate enablePredicate = criteriaBuilder.equal(enable, "ACTIVE");

Predicate middleNameAndEnablePredicate = criteriaBuilder.and(middleNamePredicate, enablePredicate);
Predicate predicate = criteriaBuilder.or(userNamePredicate, firstNamePredicate, lastNamePredicate, middleNameAndEnablePredicate);

criteriaQuery
    .select(root)
    .where(predicate);

List<EUser> list = getSession()
        .createQuery(criteriaQuery)
        .getResultList();