使用QuerydslBinderCustomizer

时间:2017-11-21 09:32:55

标签: spring spring-data-jpa querydsl spring-restcontroller

我在我的RestController中使用QuerydslPredicate对一个有日期对象的实体,我希望能够在给定日期之前/之后/之间查询日期,希望有类似的东西

  • GET / problems?createdOnAfter = XXX
  • GET / problems?createdOnBefore = YYY
  • GET / problems?createdOnAfter = XXX& createdOnBefore = YYY

我的实体有日期字段 createdOn ,我希望我可以使用多个别名自定义实体路径的绑定,即添加别名 createdOnAfter < / em> &amp; createdOnBefore - 看起来我不能创建多个别名,例如

@Repository
public interface ProblemRepository extends JpaRepository<Problem, String>, QueryDslPredicateExecutor<Problem>,
        QuerydslBinderCustomizer<QProblem> {

            ....

    @Override
    default void customize(QuerydslBindings bindings, QProblem root) {
        bindings.bind(root.createdOn).as("createdOnAfter").first(TemporalExpression::after);
        bindings.bind(root.createdOn).as("createdOnBefore").first(TemporalExpression::before);
    }
}

之前的别名显然会覆盖后一个。

避免必须手动创建谓词的正确方法是什么?

1 个答案:

答案 0 :(得分:2)

为什么不使用QueryDSL Predicate?你可以这样做:

@GetMapping("/problems")
@Timed
public ResponseEntity<List<ProblemDTO>> getAllProblems(
      @RequestParam(required = false) LocalDateTime createdOnAfter, 
      @RequestParam(required = false) LocalDateTime createdOnBefore,
      @ApiParam Pageable pageable) {
    BooleanBuilder where = new BooleanBuilder();
    if (startDate != null) {
        where = where.and(problem.createdOn.after(createdOnAfter));
    }
    if (endDate != null) {
        where = where.and(problem.createdOn.before(createdOnBefore));
    }
    Page<Donnee> page = problemRepository.findAll(where, pageable);
    return new ResponseEntity<>(problemMapper.toDTO(page.getContent())), null, HttpStatus.OK);
}

希望它有所帮助, 此致