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.
Hibernate Disjunction is used to Group expressions together in a single disjunction.
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.
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.
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.
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+"%")));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With