Criteria API:
The
interface Criteria represents a
query against a particular persistent class and Session is a factory for Criteria instances.
Criteria
crit = sess.createCriteria(Emp.class);
crit.setMaxResults(50);
List
emp = crit.list();
Getting
the Results using like,between equalto methods in Criteria API:
The
clasorg.hibernate.criterion.Restrictions defines
factory methods. An individual query criterion is an instance of the interface org.hibernate.criterion.Criterion.
List
emp = sess.createCriteria(Emp.class)
.add( Restrictions.like("name",
"Fritz%") )
.add(
Restrictions.between("weight", minWeight, maxWeight) )
.list();
condition
for group result
List
emp = sess.createCriteria(Emp.class)
.add( Restrictions.like("name",
"Fritz%") )
.add( Restrictions.or(
Restrictions.eq( "age", new
Integer(0) ),
Restrictions.isNull("age")) ).list();
List
emp = sess.createCriteria(Emp.class)
.add( Restrictions.in( "name",
new String[] { "hii", "Izi", "Pk" } ) )
.add( Restrictions.disjunction()
.add(
Restrictions.isNull("age") )
.add( Restrictions.eq("age",
new Integer(0) ) )
.add( Restrictions.eq("age",
new Integer(1) ) )
.add( Restrictions.eq("age", new
Integer(2) ) )) ) .list();
There
is a range of built-in criterion types (Restrictions subclasses). One of the most useful
allows you to specify SQL directly.
List
emp = sess.createCriteria(Emp.class)
.add(
Restrictions.sqlRestriction("lower({alias}.name) like lower(?)",
"Fritz%", Hibernate.STRING) )
.list();
The
{alias} placeholder
with be replaced by the row alias of the queried entity.
You
can also obtain a criterion from a property instance. You can create a Property by calling property.forName():
Property
age = Property.forName("age");
List
emp = sess.createCriteria(Emp.class)
.add( Restrictions.disjunction()
.add( age.isNull() )
.add( age.eq( new Integer(0) ) )
.add( age.eq( new Integer(1) ) )
.add( age.eq( new Integer(2) ) )
) )
.add(
Property.forName("name").in( new String[] { "Fritz",
"Izi", "Pk" } ) )
.list();
Display the results (asc and desc)
You
can order the results using org.hibernate.criterion.Order.
List
emp = sess.createCriteria(Emp.class)
.add( Restrictions.like("name",
"F%")
.addOrder( Order.asc("name") )
.addOrder( Order.desc("age") )
.setMaxResults(50)
.list();
List
emp = sess.createCriteria(Emp.class)
.add( Property.forName("name").like("F%")
)
.addOrder(
Property.forName("name").asc() )
.addOrder(
Property.forName("age").desc() )
.setMaxResults(50)
.list();
Associations
By
navigating associations using createCriteria() you can
specify constraints upon related entities:
List
emp = sess.createCriteria(Emp.class)
.add( Restrictions.like("name",
"F%") )
.createCriteria("kittens")
.add(
Restrictions.like("name", "F%") )
.list();
The
second createCriteria() returns a new
instance of Criteria that refers to
the elements of the kittens collection.
There
is also an alternate form that is useful in certain circumstances:
List
emp = sess.createCriteria(Emp.class)
.createAlias("kittens",
"kt")
.createAlias("mate",
"mt")
.add(
Restrictions.eqProperty("kt.name", "mt.name") )
.list();
The
kittens collections held by the Emp instances returned by the previous two
queries are not pre-filtered by the criteria. If you want to retrieve
just the kittens that match the criteria, you must use a ResultTransformer.
List
emp = sess.createCriteria(Emp.class)
.createCriteria("kittens",
"kt")
.add( Restrictions.eq("name",
"F%") )
.setResultTransformer(Criteria.ALIAS_TO_ENTITY_MAP)
.list();
Iterator
iter = emp.iterator();
while
( iter.hasNext() ) {
Map map = (Map) iter.next();
Emp emp = (Emp)
map.get(Criteria.ROOT_ALIAS);
Emp kitten = (Emp) map.get("kt");
}
Dynamic fetching
You
can specify association fetching semantics at runtime using setFetchMode().
List
emp = sess.createCriteria(Emp.class)
.add( Restrictions.like("name",
"Fritz%") )
.setFetchMode("mate",
FetchMode.EAGER)
.setFetchMode("kittens",
FetchMode.EAGER)
.list();
.
Example:
The
class org.hibernate.criterion.Example allows you to
construct a query criterion from a given instance.
Emp
emp = new Emp();
emp.setSex('F');
emp.setColor(Color.BLACK);
List
results = session.createCriteria(Emp.class)
.add( Example.create(emp) )
.list();
Version
properties, identifiers and associations are ignored. By default, null valued
properties are excluded.
You
can adjust how the Example is applied.
Example
example = Example.create(emp)
.excludeZeroes() .excludeProperty("color") .ignoreCase()
comparisons.enableLike();
List
results = session.createCriteria(Emp.class)
.add(example)
.list();
List
results = session.createCriteria(Emp.class)
.add( Example.create(emp) )
.createCriteria("mate")
.add( Example.create( emp.getMate() ) )
.list();
Projections,
aggregation and grouping
The class org.hibernate.criterion.Projections is a factory
for Projection instances. You
can apply a projection to a query by calling setProjection().
List results =
session.createCriteria(Emp.class)
.setProjection( Projections.rowCount() )
.add( Restrictions.eq("color",
Color.BLACK) )
.list();
List results =
session.createCriteria(Emp.class)
.setProjection(
Projections.projectionList()
.add( Projections.rowCount() )
.add(
Projections.avg("weight") )
.add(
Projections.max("weight") )
.add(
Projections.groupProperty("color") )
)
.list();
There
is no explicit "group by" necessary in a criteria query. Certain
projection types are defined to be grouping projections, which also
appear in the SQL group
by
clause.
An
alias can be assigned to a projection so that the projected value can be
referred to in restrictions or orderings. Here are two different ways to do
this:
List
results = session.createCriteria(Emp.class)
.setProjection( Projections.alias(
Projections.groupProperty("color"), "colr" ) )
.addOrder( Order.asc("colr") )
.list();
List
results = session.createCriteria(Emp.class)
.setProjection(
Projections.groupProperty("color").as("colr") )
.addOrder( Order.asc("colr") )
.list();
The
alias() and as() methods simply
wrap a projection instance in another, aliased, instance of Projection. As a
shortcut, you can assign an alias when you add the projection to a projection
list:
List
results = session.createCriteria(Emp.class)
.setProjection(
Projections.projectionList()
.add( Projections.rowCount(), "empCountByColor"
)
.add(
Projections.avg("weight"), "avgWeight" )
.add(
Projections.max("weight"), "maxWeight" )
.add(
Projections.groupProperty("color"), "color" )
)
.addOrder( Order.desc("empCountByColor")
)
.addOrder(
Order.desc("avgWeight") )
.list();
List
results = session.createCriteria(Domestic.class, "emp")
.createAlias("kittens",
"kit")
.setProjection(
Projections.projectionList()
.add( Projections.property("emp.name"),
"empName" )
.add( Projections.property("kit.name"), "kitName" )
)
.addOrder( Order.asc("empName") )
.addOrder( Order.asc("kitName") )
.list();
You
can also use Property.forName() to express
projections:
List results =
session.createCriteria(Emp.class)
.setProjection(
Property.forName("name") )
.add(
Property.forName("color").eq(Color.BLACK) )
.list();
List results =
session.createCriteria(Emp.class)
.setProjection(
Projections.projectionList()
.add( Projections.rowCount().as("empCountByColor")
)
.add(
Property.forName("weight").avg().as("avgWeight") )
.add(
Property.forName("weight").max().as("maxWeight") )
.add(
Property.forName("color").group().as("color" )
)
.addOrder( Order.desc("empCountByColor")
)
.addOrder(
Order.desc("avgWeight") )
.list();
Detached queries and subqueries
The
DetachedCriteria class allows
you to create a query outside the scope of a session and then execute it using
an arbitrary Session.
DetachedCriteria
query = DetachedCriteria.forClass(Emp.class)
.add(
Property.forName("sex").eq('F') );
Session
session = ....;
Transaction
txn = session.beginTransaction();
List
results = query.getExecutableCriteria(session).setMaxResults(100).list();
txn.commit();
session.close();
DetachedCriteria:
A
DetachedCriteria can also be
used to express a subquery. Criterion instances involving subqueries can be
obtained via Subqueries or Property.
DetachedCriteria
avgWeight = DetachedCriteria.forClass(Emp.class)
.setProjection(
Property.forName("weight").avg() );
session.createCriteria(Emp.class)
.add(
Property.forName("weight").gt(avgWeight) )
.list();
DetachedCriteria
weights = DetachedCriteria.forClass(Emp.class)
.setProjection(
Property.forName("weight") );
session.createCriteria(Emp.class)
.add( Subqueries.geAll("weight",
weights) )
.list();
Correlated subqueries are also
possible:
DetachedCriteria
avgWeightForSex = DetachedCriteria.forClass(Emp.class, "emp2")
.setProjection( Property.forName("weight").avg()
)
.add( Property.forName("emp2.sex").eqProperty("emp.sex")
);
session.createCriteria(Emp.class,
"emp")
.add(
Property.forName("weight").gt(avgWeightForSex) )
.list();
thanks for providing about hibernate criteria api all methods...
ReplyDelete