Fred Altman
Fred Altman

Reputation: 221

How to use Hibernate Criteria objects for multiple and/or conditions

I need to create a Hibernate criteria restriction that ors 3 Conditions. The problem is that the last condition is acutally to conditions using the AND operator.

My first condition:

Criterion startInRange = Restrictions.between("expectedStartCanonicDate", 
                                               rangeStart, rangeEnd);

My second condition:

Criterion endInRange = Restrictions.between("expectedCompletionCanonicDate", 
                                             rangeStart, rangeEnd);

MY third condition needs to AND the following two conditions together:

criteria.add(Restrictions.le("expectedStartCanonicDate", rangeStart));
criteria.add(Restrictions.ge("expectedCompletionCanonicDate", rangeEnd));

The restriction I want to do is condition1 or condition2 or condition3. I have found examples that get me close. I can use a LogicalExpression to or the first two conditions together, however, I'm not sure how to or 3 conditions, particularly when the last condition is really two separate conditions 'anded' together.

Any Thoughts? Fred

Upvotes: 13

Views: 39166

Answers (2)

user3572247
user3572247

Reputation: 11

Criteria criteriaObj = sessionselectreply.createCriteria(TaskReplyVO.class,"taskreply")
                .createAlias("taskreply.objTaskView", "taskview")
                .createAlias("objMailTo", "mailto")
                .add(Restrictions.eq("taskview.longTaskId", taskid))
                .add(Restrictions.eq("mailto.longuserid", userid));

Upvotes: 1

JB Nizet
JB Nizet

Reputation: 692161

A sequence of restrictions linked with or is called a disjunction. A sequence of restrictions linked with and is called a conjunction.

So, what you need is

  • one conjunction for your third condition
  • one disjunction to link the first, second, and third conditions:

So here it goes:

Criterion startInRange = Restrictions.between("expectedStartCanonicDate", rangeStart, rangeEnd);

Criterion endInRange = Restrictions.between("expectedCompletionCanonicDate", rangeStart, rangeEnd);

Criterion thirdCondition = 
    Restrictions.conjunction().add(Restrictions.le("expectedStartCanonicDate", rangeStart))
                              .add(Restrictions.ge("expectedCompletionCanonicDate", rangeEnd));

Criterion completeCondition = 
    Restrictions.disjunction().add(startInRange)
                              .add(endInRange)
                              .add(thirdCondition);

criteria.add(completeCondition);

Upvotes: 47

Related Questions