I have a String array named andOrButtonFilter
which stores and
or
filters selected by user.
Also two ArrayList
named column
and value
storing column names and their values respectively.
I want the current query to append to the previous query and show the results But my query is not being appended to the previous query, it is showing individual results.
For eg:
if name=xyz
is first query and
age=26
is second query
It does not results with name=xyz
and age=26
. It is only showing results for age=26
when executed for the second time.
Where am I going wrong?
This is the code I am using at the moment:
for (int i=0; i<andOrButtonFilter.length; i++)
{
if(andOrButtonFilter[i]=="and")
{
Conjunction conjunction =Restrictions.conjunction();
if ((column.get(i) != null) && (value.get(i)!=null))
{
conjunction.add(Restrictions.or(Restrictions.eq(column.get(i), value.get(i))));
criteriaQuery.add(conjunction);
}
}
else if(andOrButtonFilter[i]=="or")
{
Disjunction disjunction =Restrictions.disjunction();
if ((column.get(i) != null) && (value.get(i)!=null))
{
disjunction.add(Restrictions.or(Restrictions.eq(column.get(i), value.get(i))));
criteriaQuery.add(disjunction);
}
}
else
{
criteriaQuery.add(Restrictions.eq(column.get(i), value.get(i)));
}
}
I can find a few problems with you code.
1) You compare strings with == instead of equals. So your code always goes into the last section criteriaQuery.add(Restrictions.eq(column.get(i), value.get(i)));
2) In your conjunction/disjunction code you still use Restrictions.or which is kind of wrong. You don't even need Restrictions.or or Restrictions.and because Conjunction is adding the restrictions with AND anyway and Disjunction is adding with OR anyway.
3) On each iteration you add separate disjunction which is basically a single criterion and won't work as you expect.
I would try with something like:
Disjunction disjunction =Restrictions.disjunction();
Conjunction conjunction =Restrictions.conjunction();
for (int i=0; i<andOrButtonFilter.length; i++)
{
if("and".equals(andOrButtonFilter[i]))
{
if ((column.get(i) != null) && (value.get(i)!=null))
{
conjunction.add(Restrictions.eq(column.get(i), value.get(i)));
}
}
else if("or".equals(andOrButtonFilter[i]))
{
if ((column.get(i) != null) && (value.get(i)!=null))
{
disjunction.add(Restrictions.eq(column.get(i), value.get(i)));
}
}
else
{
criteriaQuery.add(Restrictions.eq(column.get(i), value.get(i)));
}
}
criteriaQuery.add(conjunction);
criteriaQuery.add(disjunction);
I am not saying that exact code will work because I haven't tested it ;) but you get the idea and you can debug from there.