Professional Documents
Culture Documents
Hibernate Criteria
Hibernate Criteria
This is a very convenient approach for functionality like "search" screens where there is a variable number of conditions to be placed upon the result set. The Session is a factory for Criteria. Criterion instances are usually obtained via the factory methods on Restrictions. eg. List cats = session.createCriteria(Cat.class) .add( Restrictions.like("name", "Iz%") ) .add( Restrictions.gt( "weight", new Float(minWeight) ) ) .addOrder( Order.asc("age") ) .list(); You may navigate associations using createAlias() or createCriteria().
List cats = session.createCriteria(Cat.class) .createCriteria("kittens") .add( Restrictions.like("name", "Iz%") ) .list(); List cats = session.createCriteria(Cat.class) .createAlias("kittens", "kit") .add( Restrictions.like("kit.name", "Iz%") ) .list(); You may specify projection and aggregation using Projection instances obtained via the factory methods on Projections. List cats = session.createCriteria(Cat.class) .setProjection( Projections.projectionList() .add( Projections.rowCount() ) .add( Projections.avg("weight") ) .add( Projections.max("weight") ) .add( Projections.min("weight") ) .add( Projections.groupProperty("color") ) ) .addOrder( Order.asc("color") )
Methods:
add
public Criteria add(Criterion criterion)
Add a restriction to constrain the results to be retrieved. Parameters: criterion - The criterion object representing the restriction to be applied. Returns: this (for method chaining)
setFetchMode
public Criteria setFetchMode(String associationPath, FetchMode mode) throws HibernateException
Specify an association fetching strategy for an association or a collection of values. Parameters: associationPath - a dot seperated property path mode - The fetch mode for the referenced association Returns: this (for method chaining) Throws:
HibernateException
createCriteria
public Criteria createCriteria(String associationPath, int joinType) throws HibernateException
Create a new Criteria, "rooted" at the associated entity, using the specified join type. Parameters: associationPath - A dot-seperated property path joinType - The type of join to use. Returns: the created "sub criteria" Throws:
HibernateException
setMaxResults
public Criteria setMaxResults(int maxResults)
Set a limit upon the number of objects to be retrieved. Parameters: maxResults - the maximum number of results Returns: this (for method chaining)
list
public List list() throws HibernateException
Get the results. Returns: The list of matched query results. Throws:
HibernateException