Reputation: 1546
I have the requirement where I need to use Criterion
for or
condition. This Criterion
will be created in loop. So I am adding the Criterion
into a List
. And outside of the loop I am adding these Criterion
's into Criteria
and typecasting the list(which contains the Criterion
) into Criterion[]
array.
List<Criterion> criterions = new ArrayList<Criterion>();
for (XYZ xyz : xyzs) {
Integer[] age = findMinAndMaxAgeXYZ(xyz);
Date minAge = prepareDateByAge(age[0]);
Date maxAge = prepareDateByAge(age[1]);
// Ordering has been changed to fetch the records for
// between condition.
criterions.add(Restrictions.between("dob", maxAge, minAge));
}
criteria.add(Restrictions.or((Criterion[]) criterions.toArray()));
But it gives me exception
java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to [Lorg.hibernate.criterion.Criterion;
Any other solution to add the Criterion
as or
instead of putting into the list.
Upvotes: 0
Views: 388
Reputation: 691715
toArray()
returns an array of Object. What you need is an array of Criterion. So the correct method is:
Criterion[] array = criterions.toArray(new Criterion[criterions.size()]);
See the different return type between toArray()
and toArray(T[])
Note that, in this case, it would be much easier to simply use a disjunction:
Disjunction disjunction = Restrictions.disjunction();
for (XYZ xyz : xyzs) {
...
disjunction.add(Restrictions.between("dob", maxAge, minAge));
}
criteria.add(disjunction);
Upvotes: 3