gpt4 book ai didi

java - 所有JPA规范查询之间的AND运算

转载 作者:行者123 更新时间:2023-12-01 17:44:38 25 4
gpt4 key购买 nike

我从 Controller ( map )接收查询参数,以根据提供的 map 查询数据。我想使用规范,但我不确定如何在所有规范之间进行 AND 操作。我将不胜感激任何建议。

这是我的标准类:

 public class DriverSpecs {

private final static String CAR_FIELD = "carDO";

public Specification<DriverDO> getDriversBySpecification(Map<String, String> queryParams) {

queryParams.keySet().forEach(k -> {
if (k.toLowerCase().contains("username")){
getDriversByUsername(queryParams.get(k));
} else if (k.toLowerCase().contains("rating")){
getDriversByCarRating(queryParams.get(k));
}
// ...
});


// do AND operation for all the specifications and return it
return null;
}

public static Specification<DriverDO> getDriversByUsername(String username) {
return ((root, criteriaQuery, criteriaBuilder) -> criteriaBuilder.equal(root.get("username"), username));
}

public static Specification<DriverDO> getDriversByOnlineStatus(String onlineStatus) {
return ((root, criteriaQuery, criteriaBuilder) -> criteriaBuilder.equal(root.get("onlineStatus"), onlineStatus));
}

public static Specification<DriverDO> getDriverByCarSeat(short seatCount) {
return specificationWithCarJoin("seatCount", seatCount);
}

public static Specification<DriverDO> getDriversByCarConvertableType(boolean convertible) {
return specificationWithCarJoin("convertible", convertible);
}

public static Specification<DriverDO> getDriversByCarRating(String rating) {
return specificationWithCarJoin("rating", rating.toUpperCase());
}

private static Specification<DriverDO> specificationWithCarJoin(String getField, Object field) {
return (root, criteriaQuery, criteriaBuilder) -> {
Join<DriverDO, CarDO> carJoin = root.join(CAR_FIELD);
return criteriaBuilder.equal(carJoin.get(getField), field);
};
}
}

最佳答案

为此使用 Stream API。将所有参数映射到一个规范中,然后将其简化为单个规范。像这样

Optional<Specification<DriverDO>> reduce = queryParams.keySet().stream().map(k -> {
if (k.toLowerCase().contains("username")){
return getDriversByUsername(queryParams.get(k));
} else if (k.toLowerCase().contains("rating")){
return getDriversByCarRating(queryParams.get(k));
}
// ...
}).reduce((a, b) -> a.and(b));

关于java - 所有JPA规范查询之间的AND运算,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57141241/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com