Un criterion (critère de recherche) est une instance de l'interface org.hibernate.criterion.Criterion
. La classe org.hibernate.criterion.Restrictions
définit des méthodes pour obtenir des types de Criterion
pré-définis.
List cats = sess.createCriteria(Cat.class) .add( Restrictions.like("name", "Fritz%") ) .add( Restrictions.between("weight", minWeight, maxWeight) ) .list();
Les restrictions peuvent être goupées de manière logique.
List cats = sess.createCriteria(Cat.class) .add( Restrictions.like("name", "Fritz%") ) .add( Restrictions.or( Restrictions.eq( "age", new Integer(0) ), Restrictions.isNull("age") ) ) .list();
List cats = sess.createCriteria(Cat.class) .add( Restrictions.in( "name", new String[] { "Fritz", "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();
Il y a plusieurs types de criterion pré-définis (sous classes de Restriction
), mais l'une d'entre elle particulièrement utile vous permet de spécifier directement du SQL.
List cats = sess.createCriteria(Cat.class) .add( Restrictions.sqlRestriction("lower({alias}.name) like lower(?)", "Fritz%", Hibernate.STRING) ) .list();
La zone {alias}
sera remplacée par l'alias de colonne de l'entité que l'on souhaite intérroger.
Une autre approche pour obtenir un criterion est de le récupérer d'une instance de Property
. Vous pouvez créer une Property
en appelant Property.forName()
.
Property age = Property.forName("age"); List cats = sess.createCriteria(Cat.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();