JPA 组合查询之AND和OR组合查询

前两天碰到JPA的组合查询,记之。

	public Page getUserBorrowByPage(Pageable pageable,JSONObject whereObj,JSONObject userPermission){
		Page results=financeBorrowRepository.findAll(new Specification() {
			@Override
			public Predicate toPredicate(Root root,CriteriaQueryquery,CriteriaBuilder cb){
				// 查询条件
				List listWhere=new ArrayList<>();
				if(whereObj!=null)
					for (Map.Entry entry : whereObj.entrySet()) {					
						try {
							listWhere.add(cb.like(root.get(entry.getKey()).as(String.class), "%"+entry.getValue()+"%"));						
						} catch (IllegalArgumentException e) {
							log.error("--参数["+entry.getKey()+"]不存在");
							continue;
						}					
			        }
				Predicate[] predicatesWhereArr=new Predicate[listWhere.size()];				
				Predicate predicatesWhere= cb.and(listWhere.toArray(predicatesWhereArr));
				
				//用户限制条件
				List listPermission=new ArrayList<>();
				if(userPermission!=null)
					for (Map.Entry entry : userPermission.entrySet()) {					
						try {
							listPermission.add(cb.equal(root.get(entry.getKey()).as(String.class), entry.getValue()));
							log.info(" -- "+entry.getValue());
						} catch (IllegalArgumentException e) {
							log.error("--参数["+entry.getKey()+"]不存在");
							continue;
						}					
			        }
				Predicate[] predicatesPermissionArr=new Predicate[listPermission.size()];				
				Predicate predicatesPermission= cb.or(listPermission.toArray(predicatesPermissionArr));
				
				return query.where(predicatesWhere,predicatesPermission).getRestriction();
			}
			
		},pageable);					
		return results;
	}

你可能感兴趣的:(spring,boot)