🔥码云GVP开源项目 12k star Uniapp+ElementUI 功能强大 支持多语言、二开方便! 广告
# 15.2\. 限制结果集内容 一个单独的查询条件是`org.hibernate.criterion.Criterion` 接口的一个实例。`org.hibernate.criterion.Restrictions`类 定义了获得某些内置`Criterion`类型的工厂方法。 ``` List cats = sess.createCriteria(Cat.class) .add( Restrictions.like("name", "Fritz%") ) .add( Restrictions.between("weight", minWeight, maxWeight) ) .list(); ``` 约束可以按逻辑分组。 ``` 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(); ``` Hibernate提供了相当多的内置criterion类型(`Restrictions` 子类), 但是尤其有用的是可以允许你直接使用SQL。 ``` List cats = sess.createCriteria(Cat.class) .add( Restrictions.sqlRestriction("lower({alias}.name) like lower(?)", "Fritz%", Hibernate.STRING) ) .list(); ``` `{alias}`占位符应当被替换为被查询实体的列别名。 `Property`实例是获得一个条件的另外一种途径。你可以通过调用`Property.forName()` 创建一个`Property`。 ``` 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(); ```