Gary Kephart
Gary Kephart

Reputation: 4994

Hibernate ORing two criteria

First, this is about ORing two Criteria, not two Criterion.

As part of a query, I'm trying to do this:

from voters v
left join addresses a on v.addressId = a.addressId
left join precincts p on a.areaId    = a.precinctId
left join overlaps  o on o.areaId1   = p.areaId
where p.areaId = ? or o.areaId2 = ?

and the two ? are the same value. I've gotten a bit of it, but am now stuck. Here's what I have

criteria = session.createCriteria(Voter.class);
addressCriteria = criteria.createCriteria("address");
precinctCriteria = addressCriteria.createCriteria("precinct");
overlapsCriteria = precinctCriteria.createCriteria("overlaps");

I'd like to do the following, but it doesn't work.

SimpleExpression lhs = Restrictions.eq("precinct.id", areaId);
SimpleExpression rhs = Restrictions.eq("overlaps.id", areaId);
LogicalExpression criterion = Restrictions.or(lhs, rhs);

So, what am I really supposed to do? I'm thinking it involves createAlias(...) but I'm not sure how. And to which Criteria would I add that last Criterion? The first one?

Upvotes: 2

Views: 720

Answers (1)

atrain
atrain

Reputation: 9265

Use a Disjunction:

Disjunction dis = Restrictions.disjunction();
dis.add(Restrictions.eq("precinct.id", areaId));
dis.add(Restrictions.eq("overlaps.id", areaId));
criteria.add(dis);

Note that you might need to alias precinct and overlaps.

Upvotes: 2

Related Questions