JPA CriteriaBuilder子查询

//根据id集合查询

List<Long> idList = mainUserDTO.getIdList();
if (null != idList && !idList.isEmpty()) {
    Path<Long> idSearchPath = root.get(MainUser_.id);
    CriteriaBuilder.In<Long> in = criteriaBuilder.in(idSearchPath);
    idList.stream().forEach(id -> in.value(id));
    if (null != where) {
        where = criteriaBuilder.and(where, criteriaBuilder.and(in));
    } else {
        where = criteriaBuilder.and(in);
    }
}

//排除id集合查询

List<Long> excludeIdList = mainUserDTO.getExcludeIdList();
if (null != excludeIdList && !excludeIdList.isEmpty()) {
    Path<Long> idSearchPath = root.get(MainUser_.id);
    CriteriaBuilder.In<Long> in = criteriaBuilder.in(idSearchPath);
    excludeIdList.stream().forEach(id -> in.value(id));
    if (null != where) {
        where = criteriaBuilder.and(where, criteriaBuilder.not(in));
    } else {
        where = criteriaBuilder.not(in);
    }
}

//根据多个参数模糊查询

String likeQueryParam = mainUserDTO.getLikeQueryParam();
if (StrUtils.isNotBlank(likeQueryParam)) {
    Path<String> userCodeSearchPath = root.get(MainUser_.userCode);
    Path<String> phoneSearchPath = root.get(MainUser_.phone);
    Path<String> userNameSearchPath = root.get(MainUser_.userName);
    if (null != where) {
        where = criteriaBuilder.and(where, criteriaBuilder.or(criteriaBuilder.like(userCodeSearchPath, "%" + likeQueryParam + "%"),
                criteriaBuilder.or(criteriaBuilder.like(phoneSearchPath, "%" + likeQueryParam + "%")),
                criteriaBuilder.or(criteriaBuilder.like(userNameSearchPath, "%" + likeQueryParam + "%"))));
    } else {
        where = criteriaBuilder.and(criteriaBuilder.like(userCodeSearchPath, "%" + likeQueryParam + "%"),
                criteriaBuilder.or(criteriaBuilder.like(phoneSearchPath, "%" + likeQueryParam + "%")),
                criteriaBuilder.or(criteriaBuilder.like(userNameSearchPath, "%" + likeQueryParam + "%")));
    }
}

//关联表数据查询

String appNameSearch = userAppDTO.getAppName();
if (appNameSearch != null) {
   List<Long> appIds = applicationService.findList(ApplicationDTO.builder().appName(appNameSearch).build())
           .stream().map(Application::getId).collect(Collectors.toList());
   if (Objects.nonNull(appIds) && !appIds.isEmpty()) {
       Path<Long> appIdSearchPath = root.get(UserApp_.appId);
       CriteriaBuilder.In<Long> in = criteriaBuilder.in(appIdSearchPath);
       appIds.forEach(appId -> in.value(appId));
       if (null != where) {
           where = criteriaBuilder.and(where, criteriaBuilder.and(in));
       } else {
           where = criteriaBuilder.and(in);
       }
   }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值