hibernate or连接查询内容/criteria动态或连接查询/disjunction/其他查询条件

在查询时,会进行多个id的查询,这是查询语句为
select  * from table where id = 'XXX'  or  id = ‘XX’
在使用hibernate的查询使用方法为:
    可以使用Disjunction来拼接查询条件
代码示例:
    @Override
    public String beforeQuery(Criteria criteria) throws Exception {
        Disjunction disjunction =     Restrictions.disjunction();;
        if(invocieId!=null && !"".equals(invocieId)){
            String[] ids  = invocieId.split(",");
            for(int i = 0 ;i < ids.length ; i++){
                disjunction.add(Restrictions.eq("inventoryId", ids[i]));
            }
            criteria.add(disjunction);
        }
        return super.beforeQuery(criteria);
    }

hibernate 限制结果集

一个单独的查询条件是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(); 







posted @ 2013-11-20 23:40  thero  阅读(932)  评论(0编辑  收藏  举报