Reputation: 83
Hello,I am new to Hibernate and i was trying to execute and() method in Hibernate Criteria Queries using Eclipse but the LogicalExpression will show error like
The method and(Criterion, Criterion) in the type Restrictions is not applicable for the arguments (Criteria, Criteria)
package actions;
import java.util.Iterator;
import java.util.List;
import org.hibernate.Criteria;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.hibernate.criterion.LogicalExpression;
import org.hibernate.criterion.Restrictions;
public class Andrestriction {
public static void main(String[] args) {
// TODO Auto-generated method stub
SessionFactory sf=new Configuration().configure().buildSessionFactory();
Session sn=sf.openSession();
Criteria cr=sn.createCriteria(PC.class);
Criteria id=(Criteria) Restrictions.gt("id",11);
Criteria os=(Criteria) Restrictions.ilike("os","d%");
LogicalExpression and=Restrictions.and(id,os); //This line will show error like this:-
//The method and(Criterion, Criterion) in the type Restrictions is not
//applicable for the arguments (Criteria, Criteria)
cr.add(and);
List l=cr.list();
Iterator itr=l.iterator();
while(itr.hasNext())
{
PC p=(PC)itr.next();
System.out.println(p.getId()+"\t"+p.getName()+"\t"+p.getOs());
}
sn.close();
}
}
I want to use and criteria in my Query.Please tell me how to Solve this problem. Thanks in advance
Upvotes: 0
Views: 1858
Reputation: 2206
Restrictions.gt() returns a SimpleExpression which is a Criterion (implements Criterion)
So you should not cast a SimpleExpression to a Criteria. You already have a criteria ( You create one criteria which actually transforms into a query and executed on database ), so what you need is:
Criteria cr=sn.createCriteria(PC.class);
Criterion id=Restrictions.gt("id",11); // No need to cast as SimpleExpression implements Criterion
Criterion os= Restrictions.ilike("os","d%");
LogicalExpression and=Restrictions.and(id,os);
cr.add(and);
A compiler error shows up because you are passing two Criteria objects to and() method of Restriction class but it expects Criterion objects. So change it as above and you are good to do.
Upvotes: 1
Reputation: 61865
As the error message indicates there is no matching Restrictions.and
method with the given signature. When encountering these type-errors the first place that should be consulted is the documentation - then work back resolving the expected/actual types.
To fix this, drop the (invalid) cast and use the correct type for the variable;
// Criterion, not Criteria - also no cast
Criterion id = Restrictions.gt("id",11);
Criterion os = Restrictions.ilike("os","d%");
// Now it matches `and(Criterion, Criterion)`
LogicalExpression and = Restrictions.and(id, os);
Criteria (or criterions) are a collection of criterion; but modern English usage is a bit lax.
Upvotes: 0