black sensei
black sensei

Reputation: 6678

Working with hibernate multiple Criteria with logical AND

So far i've been working with only a case with 2 properties with and as logical operator so i use LogicalExpression like so

Criterion eqRef = Restrictions.eq("referenceID", referenceId);
Criterion eqType = Restrictions.eq("verificationType", type);
LogicalExpression and = Restrictions.and(eqRef, eqType);

this time along its more than 2 so i'm a bit confused.say this time i've added username property i can do the normal chaining with

session.createCriteria(this.getPersistentClass())
.add(Restrictions.eq("referenceID", referenceId))
.add(Restrictions.eq("verificationType", type))
.add(Restrictions.eq("username", username))
.list();

but now i don't know which kind of logical operator used between them.i'm also tempted to do this:

Criterion eqRef = Restrictions.eq("referenceID", referenceId);
Criterion eqType = Restrictions.eq("verificationType", type);
Criterion equsername = Restrictions.eq("username", username);
LogicalExpression and = Restrictions.and(eqRef, eqType);
LogicalExpression secondand = Restrictions.and(and, equsername);

i've see the eqAll too but i've never used it before.So do you have any idea about that?How do you do it, and thanks for reading this.

Upvotes: 7

Views: 23696

Answers (4)

irbef
irbef

Reputation: 11

just use this

criteria = session.createCriteria(Model.class).add(
                             Restrictions.between("ModelDate", dateMin, dateMax));

Upvotes: -1

lucas
lucas

Reputation: 6981

but now i don't know which kind of logical operator used between them.

Good answers already, but as an aside you can use the property hibernate.show_sql, set it to true, and you'll be able to see exactly what sql your criteria is producing.

Upvotes: 0

Yuval
Yuval

Reputation: 8097

Adding these restrictions individually creates a relation of 'AND' between them. This is good enough for what you need.

Upvotes: 1

Steve B.
Steve B.

Reputation: 57333

Since you're "AND"-ing all of your restrictions the grouping is irrelevant, so you can just continue on as in your second example, as there's nothing to be gained by subgrouping them, e.g.

.add(Restrictions.eq("referenceID", referenceId)).add(Restrictions.eq("verificationType", type)).add(Restrictions.eq("username", username))...

You do run into this problem where you need to group mixed "AND" and "OR" queries, if you want to group multiple "OR" values you can also add Criteria to a Disjunction

Upvotes: 12

Related Questions