逻辑运算符OR的JPA Criteria构建器

时间:2014-07-28 06:19:15

标签: jpa criteria-api

我需要动态地准备一个类似下面的查询,我在另一个列表中的组列和不同列表中的主列, 有人可以帮助我吗?

    SELECT * FROM TABLE WHERE COLUMN_A =1 ? OR (COLUMN_B='A' AND COLUMN_B='Z')

Java代码:

    CriteriaBuilder builder;
    List<Predicate> predicates = new ArrayList<Predicate>();
    List<Predicate> innerPredicates = new ArrayList<Predicate>();
    List<Predicate> outerPredicates = new ArrayList<Predicate>();

    for(GroupClause gc : list.getGroupClause()){
        List<Predicate> groupPredicates = new ArrayList<Predicate>();
        groupPredicates.add(gc.getColumnB());

        if(groupPredicates!=null && groupPredicates.size()>0){
            innerPredicates.add(builder.and(groupPredicates.toArray(new Predicate[groupPredicates.size()])));
        }
    }

    if(outerPredicates.size()>0){
        predicates.add(builder.or(outerPredicates.toArray(new Predicate[outerPredicates.size()])));
        predicates.add(builder.or(innerPredicates.toArray(new Predicate[innerPredicates.size()])));
    }

上面代码的放置是

    SELECT * FROM TABLE WHERE COLUMN_A =1 ? AND COLUMN_B='A' AND COLUMN_B='Z'

1 个答案:

答案 0 :(得分:-1)

使用简单标准这里是示例

public List<TABLE> getTABLE () {

        Criteria tableCriteria= session.createCriteria(TABLE.class);
        tableCriteria.setResultTransformer(CriteriaSpecification.DISTINCT_ROOT_ENTITY);
         tableCriteria.add(Restrictions.and(Restrictions.eq("COLUMN_A",1),Restrictions.or(Restrictions.eq("COLUMN_B","A"),
               Restrictions.eq("COLUMN_B","Z")))


        return tableCriteria.list();
    }