Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

iterate array to create hibernate criteria statement

Tags:

java

hibernate

let say my array has 3 integer object value= 3,4,5 i would need to create hibernate criteria that look like below

criteria.add(Restrictions.and(Restrictions.not(Restrictions.eq(
        "stepId", new Integer(3))), Restrictions.and(Restrictions
        .not(Restrictions.eq("stepId", new Integer(4))), Restrictions
        .not(Restrictions.eq("stepId", new Integer(5))))));

the above criteria is created manually, i wonder can automate this through iteration

for(Iterator iterator = integerArray.iterator; iterator.hasNext()){
    // create the criteria above
}
like image 410
cometta Avatar asked Dec 02 '22 06:12

cometta


2 Answers

Yes, you can use Disjunction in your loop:

Disjunction disjunction = Restrictions.disjunction();
for(Iterator iterator = integerArray.iterator; iterator.hasNext()){
    disjunction.add(yourRestriction); //add your restirction here
}
criteria.add(disjunction );
like image 84
o.k.w Avatar answered Jan 05 '23 12:01

o.k.w


You can use in restriction while takes Array argument.

  Integer[] integerArray = ...
  criteria.add(Restrictions.and(Restrictions.not(
        Restrictions.in("stepId", integerArray)
  );
like image 28
Chandra Patni Avatar answered Jan 05 '23 13:01

Chandra Patni