Hibernate- Disjunction with criterion.Example in QBE

257 views Asked by At

I want to search my database with a criterion.Example on multiple fields, OR'd together. That is, I want to retrieve records in which "field1" is an example of my search object OR "field2" is an example of my search object, where field1 and field2 are children of a top level object and each one is the same type as my search object.

What I'd like to do is

 Disjunction or = Restrictions.disjunction(); 
 or.add(criteria.createCriteria("field1").add(searchObj));
 or.add(criteria.createCriteria("field2").add(searchObj)); 
 criteria.add(or); 

Which doesn't work because Disjunctions only work with criterion and not criteria.

I tried

 Disjunction or = Restrictions.disjunction(); 
 or.add(Restrictions.eq("field1", searchObj));
 or.add(Restrictions.eq("field2", searchObj));
 criteria.add(or); 

But that gave me a PropertyAccessException on the primary key for the object, saying

 IllegalArgumentException occurred calling getter of [.....].pk

Is there any way to do a QBE with a disjunction between the example clauses?

1

There are 1 answers

0
DFL On

I solved this by using DetachedCriteria and subqueries:

DetachedCriteria f1Crit = DetachedCriteria.forClass(SearchObj.class, "field1");
f1Crit.add(searchObj); 
f1Crit.setProjection(Property.forName("id"));

DetachedCriteria f2Crit = DetachedCriteria.forClass(SearchObj.class, "field2");
f2Crit.add(searchObj); 
f2Crit.setProjection(Property.forName("id"));

criteria.add(
    Restrictions.or(
        Subqueries.propertyIn("field1.id", f1Crit),
        Subqueries.propertyIn("field2.id", f2Crit))
    );