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();
Restriction(制限)は論理的にグループ化できます。
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();
様々なCriterion 型(Restrictions のサブクラス)が同梱されていますが、最も有用なものの1つとして 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();