JPA_复杂动态查询的例子

/**
	SELECT
		article0_.*
	FROM
		kmc_article article0_
		INNER JOIN kmc_article_label articlelab1_ ON article0_.id = articlelab1_.article_id 
		AND ( articlelab1_.label_id =? ) 
	WHERE
		article0_.type = 1 
		AND article0_.STATUS =? 
		AND article0_.sort_num = 2147483647 
	ORDER BY
		article0_.sort_num DESC,
		article0_.update_time DESC 
		LIMIT ?
*/
// 链接查询 join on
mrywTopPage = articleRepository.findAll((root, query, cb) -> {
    List<Predicate> predicateList = new ArrayList<>();
    if (!itemId.equals("all")) {
        Join<Article, ArticleLabel> articleLabelJoin = root.join("articleLabels", JoinType.INNER);
        articleLabelJoin.on(cb.equal(articleLabelJoin.get("id").get("labelId"), itemId));
    }
    if (labelList.size() > 0) {
        Join<Article, ArticleLabel> labelJoin = root.join("articleLabels", JoinType.INNER);
        labelJoin.on(labelJoin.get("id").get("labelId").in(labelList));
    }
    predicateList.add(cb.equal(root.get("type"), 1));
    predicateList.add(cb.equal(root.get("status"), "已发布"));
    predicateList.add(cb.notEqual(root.get("sortNum"), 2147483647));
    query.where(predicateList.toArray(new Predicate[]{}));
    query.orderBy(cb.desc(root.get("updateTime")));
    return null;
}, pageable);
/**
 * 子查询
 * 查询在纽约工作的所有员工
 * select * from employee where DEPTNO = (
		select DEPTNO from DEPT 
		where location = 'NEW YORK' 
		AND dname like '%ACC%') ORDER BY empno desc
 */
public Page<Employee> findSubquery(Pageable pageable) {
    Page<Employee> page = employeeRepository.findAll((root, criteriaQuery, criteriaBuilder) -> {
        List<Predicate> predicateList = new ArrayList<>();
        // Subquery 表示新建一个子查询语句,泛型是主键类型
        Subquery<Integer> deptSubquery = criteriaQuery.subquery(Integer.class);
        // 根据子查询所要使用的表建立一个相应的root供它获取该表属性
        Root<Dept> deptRoot = deptSubquery.from(Dept.class);
		
        List<Predicate> deptPredicateList = new ArrayList<>();
        deptPredicateList.add(criteriaBuilder.equal(deptRoot.get("location"), "NEW YORK"));
        deptPredicateList.add(criteriaBuilder.like(deptRoot.get("dname"),"%ACC%"));
        // 将子查询的条件构建成一个完整的select语句   把子查询的结果选出id出来给外查询用
        deptSubquery.select(deptRoot.get("deptno")).where(deptPredicateList.toArray(new Predicate[]{}));
        //deptSubquery.select(deptRoot.get("deptno")).where(deptPredicate);  单个条件可用
		
        predicateList.add(root.get("dept").get("deptno").in(deptSubquery));
        // 构建整个完整的查询语句
        criteriaQuery.where(predicateList.toArray(new Predicate[]{}));
        // 增加排序功能,按照employee的empno降序
        criteriaQuery.orderBy(criteriaBuilder.desc(root.get("empno")));
        return null;
    }, pageable);
    return page;
}

你可能感兴趣的:(例子)