Java Reference
In-Depth Information
If we want to have two restrictions that return objects that satisfy either or both of the
restrictions, we need to use the or() method on the Restrictions class, as follows:
Criteria crit = session.createCriteria(Product.class);
Criterion price = Restrictions.gt("price",new Double(25.0));
Criterion name = Restrictions.like("name","Mou%");
LogicalExpression orExp = Restrictions.or(price,name);
crit.add(orExp);
List results = crit.list();
The orExp logical expression that we have created here will be treated like any other crite-
rion. We can therefore add another restriction to the criteria:
Criteria crit = session.createCriteria(Product.class);
Criterion price = Restrictions.gt("price",new Double(25.0));
Criterion name = Restrictions.like("name","Mou%");
LogicalExpression orExp = Restrictions.or(price,name);
crit.add(orExp);
crit.add(Restrictions.ilike("description","blocks%"));
List results = crit.list();
If we wanted to create an OR expression with more than two different criteria, we would
use an org.hibernate.criterion.Disjunction object to represent a disjunction. You can
obtain this object from the disjunction() factory method on the Restrictions class. The
disjunction is more convenient than building a tree of OR expressions in code. To represent
an AND expression with more than two criteria, you can use the conjunction() method—
although you can easily just add those to the Criteria object. The conjunction is also more
convenient than building a tree of AND expressions in code. Here is an example that uses
the disjunction:
Criteria crit = session.createCriteria(Product.class);
Criterion price = Restrictions.gt("price",new Double(25.0));
Criterion name = Restrictions.like("name","Mou%");
Criterion desc = Restrictions.ilike("description","blocks%");
Disjunction disjunction = Restrictions.disjunction();
disjunction.add(price);
disjunction.add(name);
disjunction.add(desc);
crit.add(disjunction);
List results = crit.list();
The last type of restriction is the SQL restriction sqlRestriction() . This restriction allows
you to directly specify SQL in the Criteria API. This is useful if you need to use SQL clauses that
Hibernate does not support through the Criteria API. Your application's code does not need to
know the name of the table your class uses—use {alias} to signify the class's table, as follows:
Criteria crit = session.createCriteria(Product.class);
crit.add(Restrictions.sqlRestriction("{alias}.name like 'Mou%'"));
List results = crit.list()
Search WWH ::




Custom Search