admin管理员组

文章数量:1406308

I have three specifications that, I would like to combine into one.

static Specification<Car> hasCarModel(List<String> modelsList) {
  return (car, cq, cb) -> cb.and(car.get("model").in(modelsList));
}

static Specification<Car> hasCreatedDateGreaterThanOrEqualToStartDate(LocalDateTime _startDate) {
  return (car, cq, cb) -> cb.greaterThanOrEqualTo(car.get("carCreatedDate"), _startDate);
}

static Specification<Car> hasCreatedDateLessThanOrEqualToEndDate(LocalDateTime _endDate) {
   return (car, cq, cb) -> cb.lessThanOrEqualTo(car.get("carCreatedDate"), _endDate);
}

Is this doable? If so, how would you do it?

I have three specifications that, I would like to combine into one.

static Specification<Car> hasCarModel(List<String> modelsList) {
  return (car, cq, cb) -> cb.and(car.get("model").in(modelsList));
}

static Specification<Car> hasCreatedDateGreaterThanOrEqualToStartDate(LocalDateTime _startDate) {
  return (car, cq, cb) -> cb.greaterThanOrEqualTo(car.get("carCreatedDate"), _startDate);
}

static Specification<Car> hasCreatedDateLessThanOrEqualToEndDate(LocalDateTime _endDate) {
   return (car, cq, cb) -> cb.lessThanOrEqualTo(car.get("carCreatedDate"), _endDate);
}

Is this doable? If so, how would you do it?

Share Improve this question edited Mar 9 at 4:15 Ferry To 1,5693 gold badges39 silver badges55 bronze badges asked Mar 5 at 21:27 Bondo KalomboBondo Kalombo 413 bronze badges
Add a comment  | 

1 Answer 1

Reset to default 0

Yes, it is possible to combine the specifications into one. we have to use Specification API in Spring Data to combine. You can combine the specifications using the and() and or() methods.

here's how yu can do it.

Specification<Car> combinedSpecification(List<String> modelsList, LocalDateTime startDate, LocalDateTime endDate) 
{
     return Specification.where(hasCarModel(modelsList))
             .and(hasCreatedDateGreaterThanOrEqualToStartDate(startDate))             
             .and(hasCreatedDateLessThanOrEqualToEndDate(endDate)); 
}

本文标签: javaIs it possible to combine three Spring Data Specifications into oneStack Overflow