JPA组合查询之AND和OR查询、多表JOIN查询、范围IN查询

Spring Data JPA 最近遇到的有关复杂查询,用复杂查询 Specification 处理。

JPA组合复杂查询:

  1. And 和 Or 查询
  2. 多表连表查询 Join
  3. 范围查询 In

代码如下:

		List<String> employeeIds = ["反射","千里","王湾"];
		
		Page<Attendance> findAll = attendanceRepository.findAll(new Specification<Attendance>() {
			private static final long serialVersionUID = 424488123558533825L;

			@Override
			public Predicate toPredicate(Root<Attendance> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder cb) {
			
				// AND查询
				List<Predicate> predicates = new ArrayList<>();
				predicates.add(cb.between(root.get("repDate").as(String.class),
					monthAttendanceParam.getYearAndMonth() + "-01",
					monthAttendanceParam.getYearAndMonth() + "-31"));
				// IN查询
				In<String> in = cb.in(root.get("employeeId"));
				for(String string : employeeIds){
					in.value(string);
				}
				predicates.add(in);
				// JOIN查询
				Join<Employee, Attendance> join = root.join("employeeName", JoinType.LEFT);
				predicates.add(cb.equal(join.get("employeeName"), monthAttendanceParam.getEmployeeName()));
				Predicate and = cb.and(predicates.toArray(new Predicate[0]));

				// OR查询
				List<Predicate> predicatesOr = new ArrayList<>();
				predicatesOr.add(cb.equal(root.get("employeeId"), "7777"));
				Predicate or = cb.or(predicatesOr.toArray(new Predicate[0]));

				return criteriaQuery.where(and, or).getRestriction();
			}
		}, pageable);
		
		System.out.println("信息:" + findAll.getContent());


你可能感兴趣的:(springdatajpa)