则成の随笔

记录一点日常和工作的收获

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::

 exp:

        CriteriaQuery<ProductCategory> criteriaQuery = criteriaBuilder.createQuery(ProductCategory.class);
        Root<ProductCategory> root = criteriaQuery.from(ProductCategory.class);
        criteriaQuery.select(root);
        Predicate restrictions = criteriaBuilder.conjunction();
        restrictions = criteriaBuilder.and(restrictions,criteriaBuilder.equal(root.get("parent"), productCategory));
        if(isProductContained != null){
            Subquery<Product> subquery1 = criteriaQuery.subquery(Product.class);
            Root<Product> subRoot1 = subquery1.from(Product.class);
            Path<Object> path = subRoot1.get("productCategory");
            
            subquery1.select(subRoot1);
            Predicate restrictions1 = criteriaBuilder.conjunction();
            restrictions1 = criteriaBuilder.and(restrictions1, criteriaBuilder.equal(subRoot1.get("productCategory"),root));
            
            Subquery<ProductCategory> subquery2 = criteriaQuery.subquery(ProductCategory.class);
            Root<ProductCategory> subRoot2 = subquery2.from(ProductCategory.class);
            subquery2.select(subRoot2);
            Predicate restrictions2 = criteriaBuilder.conjunction();
            restrictions2 = criteriaBuilder.and(restrictions2, criteriaBuilder.like(subRoot2.<String> get("treePath"),"%,"+subRoot1.get("productCategory").get("id")+",%"));
            subquery2.where(restrictions2);
            
            restrictions1 = criteriaBuilder.or(restrictions1, criteriaBuilder.in(path).value(subquery2));
            subquery1.where(restrictions1);
            restrictions = criteriaBuilder.and(restrictions,criteriaBuilder.exists(subquery1));
        }
        criteriaQuery.where(restrictions);
        criteriaQuery.orderBy(criteriaBuilder.asc(root.get("order")));
        TypedQuery<ProductCategory> typeQuery = entityManager.createQuery(criteriaQuery);
        
        if(count!=null){
            typeQuery.setMaxResults(count);
        }
        return typeQuery.getResultList();

1,CriteriaQuery<ProductCategory>相当于Select ProductCategory要查什么泛型就是什么

2,equal的括号里面两个参数分别是类的属性和值,属性可以使用root.get("productCategory").get("name").get……来写,可以免于直接使用表连接

3,subquery2子查询相当于给ProductCategory相当于查询Category的子类,通过treepath的like方法进行匹配,可以查出的结果给予subquery1作为另一个条件,restrictions1合并了restriction2(通过subquery2使用restriction2),这样subquery1相当于创造了两个条件restrictions中间使用or关键字链接,这样subquery1相当于成了一个复合条件了

5,subquery1查询是一个完整的查询查询出来是一个ProductCategory的集合,使用CriteriaBuilder.exists(subquery1)相当于在subquery1中查询出集合不能为空或数量不能为0,这样就形成了typequery的一个条件。这养就组成了一个有多个子查询的复杂的查询语句了。

posted on 2017-03-20 16:57  江则成  阅读(318)  评论(0编辑  收藏  举报