Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hibernate Restrictions.in vs. Disjunction

Other than less code, what is the difference between the following two approaches to building an IN clause using the Hibernate Criteria API? Are there performance concerns? Is there some logic in the retrieval I am missing? They both seem to perform the same as far as rows returned.

Disjunction disj = Restrictions.disjunction();
for (String value : stringArray) {
     disj.add(Restrictions.eq("code", value));
}
where.add(disj);

VS.

Restrictions.in("code", stringArray);

The reason I ask is because I am refactoring legacy code where the former exists, but I was expecting the latter. If they are both the same, I am going to leave the legacy code alone.

like image 839
sma Avatar asked May 05 '11 18:05

sma


People also ask

What is hibernate Disjunction?

Hibernate Disjunction is used to Group expressions together in a single disjunction.

What is restriction in hibernate criteria?

The Criteria interface makes it easy to selectively fetch the data on the basis of conditions in the select query. The Restriction class in hibernate provide several methods that can be used as conditions (also known as Criterion). These conditions are added to a criteria object with the add() method.

How can we join two criteria in hibernate?

Conjunction . The Restrictions. conjunction() method returns a Conjunction . The Disjunction and Conjunction classes provide add() methods to apply an OR or an AND, respectively, between the criteria.


2 Answers

Hibernate Disjunction is used to

      Group expressions together in a single disjunction

which means, if you have to compare against values X OR Y OR Z conditionally, you may iterate over and apply selective disjunction

So ideally in your case Restrictions.in and Restrictions.Disjunction does the same thing, i prefer the former in this case.

like image 94
Narayan Avatar answered Sep 21 '22 12:09

Narayan


Restrictions.Disjunction gives us explicit control , for example it allows like operator, where as in operator does not .

For example:

criteria.add(Restrictions.disjunction()
                        .add(Restrictions.eq("bill.stateCd", null))
                        .add(Restrictions.eq("bill.stateCd", ""))
                        .add(Restrictions.ilike("bill.stateCd","%"+stateCd+"%")));

cant be achieved with in

criteria.add(Restrictions.in("bill.stateCd", Arrays.asList(null,"", "%"+stateCd+"%")));
like image 27
chalikir Avatar answered Sep 19 '22 12:09

chalikir