如何在 JPA 中将条件生成器与数组列表一起应用?

How to apply a criteria builder together with an arraylist in JPA?

我正在尝试在我的 api 中接收一个包含城市名称的数组,并创建一个过滤器,其中包含 returns 该城市列表的标准 bulder。

这是我控制器中的内容

@GetMapping("/weather")
    public @ResponseBody List<Weather> weatherGetALL(
            @RequestParam(required = false) String order,
            @RequestParam(required = false) List<String>  city,
            @DateTimeFormat(pattern = DATE_PATTERN) Date date) {
            return this.weatherService.findAll(order, city, date);
    }

这就是我在服务中应用这些类型的过滤器

@Autowired
WeatherRepository _weatherRepo;

public Weather save(Weather weather) {
    return this._weatherRepo.save(weather);
}

public Weather findeById(Integer id) {
    return this._weatherRepo.findById(id).orElse(null);
}


public List<Weather> findAll(String order, List<String>  city, Date date  ) {

    List<Weather> weather  = this._weatherRepo.findAll((Specification<Weather>)(root, cq, cb) -> {
        Predicate p = cb.conjunction();

        if(!(city == null)){
            System.out.println("entra en el arreglo");  

//          for (String name : city) {
//              p = cb.and(p, cb.equal(root.get("city"), name));
//          }


        }

        /*if (!StringUtils.isEmpty(city)) {
        System.out.println("ciudad:" + name);
            p = cb.and(p, cb.equal(root.get("city"), city ));
        }*/

        if (Objects.nonNull(date)) {
            p = cb.and(p, cb.equal(root.get("date"), date ));
        }


        if (!StringUtils.isEmpty(order)) {
            if (!StringUtils.isEmpty(order)) {
                switch(order) {
                    case "date":
                        cq.orderBy(cb.asc(root.get("date")));
                        break;
                    case "-date":
                        cq.orderBy(cb.desc(root.get("date")));
                        break;
                    default:
                        cq.orderBy(cb.asc(root.get("id")));
                }
            }
        }



        return p;
    });

    return weather;

}

我读到过使用“in”运算符可以做到这一点,但我还没有找到正确的应用方法。显然我收到的一切都很好,唯一让我失望的是那部分的过滤

试试这个

public List<Weather> findAll(String order, List<String> city, Date date) {
   List<Weather> weather  = this._weatherRepo.findAll((Specification<Weather>) (root, cq, cb) -> {
            final List<Predicate> predicates = new ArrayList<>();

            if (date != null) {
                predicates.add(cb.equal(root.get("date"), date));
            }

            if (city != null && !city.isEmpty()) {
                predicates.add(root.get("city").in(city));
            }

            if (order != null && order.equals("-date")) {
                cq.orderBy(cb.desc(root.get("date")));
            } else {
                cq.orderBy(cb.asc(root.get("date")));
            }

//            return cb.or(predicates.toArray(new Predicate[]{}));
            return cb.and(predicates.toArray(new Predicate[]{}));
        });
  
   return weather;
}