17

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.

Mikko Maunu
  • 41,366
  • 10
  • 132
  • 135
sma
  • 9,449
  • 8
  • 51
  • 80

3 Answers3

17

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.

Narayan
  • 6,031
  • 3
  • 41
  • 45
  • Seems like the 2nd approach is more concise, with no need for looping. Your explanation makes sense, though. Thank you. – sma May 05 '11 at 21:01
  • 1
    @sma: when i say former, i was referring to the 1st(Restrictions.in) in my post, and not your post :) – Narayan May 06 '11 at 05:04
11

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+"%")));
chalikir
  • 133
  • 2
  • 6
3

With the given code those two behave very differently when stringArray does have zero elements.

Using Disjunction with zero expressions produces valid SQL query with 1=1 or equivalent.

Restrictions.in leads to IN operator without values, which is often (maybe some SQL dialect can handle it though) syntactically incorrect.

Mikko Maunu
  • 41,366
  • 10
  • 132
  • 135