QueryDsl: Customize predicate with Rest Controller

21 Views Asked by At
public Page<DemoDto> find(
    @QuerydsPredicate(root = DemoEntiy.class) final Predicate predicate,
    @PageableDefault(size = 100)
    @SortDefault(sort = "id", direction = Sort.Direction.ASC) Pageable pageable,
    @RequestParam MultiValueMap<String, String> parameters) {
        if (IRequestValidator.isValidParams(parameters)) {
            throw new ResponseStatusException(HttpStatus.BAD_REQUEST,
                "Search params have incorrect values or range is too high.");
        }
        return DemoEntiyService.findAllByQueryDsl(
            QueryDslUtil.validPredicate(predicate, parameters), pageable);
}

The predicate will ignore the params which doesnt have matching name in the entity class.

I am passing startDate and endDate as parameters in the request "?startDate=<some_date>&endDate=<some_date2>".Entity have only createdOn.

Question - How can i create/customize the predicate to have something like condition of createdOn b/w startDate and endDate

In case anyone interested in the repository

public interface DemoRepository
extends JpaRepository<DemoEntity, Long>, QuerydsPredicateExecutor<DemoEntity> {}
1

There are 1 best solutions below

0
xtreme On

You can achive to filter this using specifications of JPA. Here example:

RestController:

@GetMapping
public Page<DemoDto> search(@Valid DemoCriteria criteria, Pageable pageable) {
  return service.search(criteria, pageable);
}

Service:

public Page<DemoDto> search(DemoCriteria criteria, Pageable pageable) {
  Specification<Demo> spec = Specification.where(null);
  if(criteria.getStartDate() != null) {
    spec = spec.and((root, query, builder) -> {
      return builder.greaterThanOrEqualTo(root.get("startDate"), criteria.getStartDate()))
  }
  //... other specifications
  return repository.findAll(spec, pageable).map(this::mapToDto);
}

public DemoDto mapToDto(Demo entity) {
//TODO mapping
}

Repository:

@Repository
public interface DemoRepository extends JpaRepository<Demo, Long>, JpaSpecificationExecutor<Demo> {
}