CriteriaBuilder,参数:查找具有特定对象的用户

时间:2019-02-28 12:33:12

标签: spring-boot spring-data-jpa

我正在尝试按权限(许可证和资料)筛选用户。现在,我正在尝试各种可能性,但我觉得自己陷于困境,正在寻求帮助。

@PreAuthorize("hasAuthority('service_manager')")
    @RequestMapping(path = "/workers", method = RequestMethod.GET)
    public Page<WorkDetailResponse> getWorkers(
            @RequestParam(defaultValue = "0") Integer page,
            @RequestParam(defaultValue = "10") Integer size,
            @RequestParam(required = false) String name,
            @RequestParam(required = false) BigInteger phone,
            @RequestParam(required = false) String email,
            @RequestParam(required = false) String competences,
            @RequestParam(required = false) User.UserStatus status,
            @RequestParam(defaultValue = "createTime") String sort,
            @RequestParam(defaultValue = "desc") String sortDir
            ){

        WorkDetailListRequest request = new WorkDetailListRequest(name, phone, email, competences, roles, status);

        Sort.Direction direction;

        if (sortDir.equals("asc")) {
            direction = Sort.Direction.ASC;
        } else {
            direction = Sort.Direction.DESC;
        }

        return workDetailService.getWorkDetails(request, of(page, size, direction, sort))
                .map(WorkDetailResponse::new);
    }

一个工人的能力实际上是一组能力对象[],一个工人可以具有许多能力。

public Page<WorkDetail> getWorkDetails(WorkDetailListRequest request, Pageable pageable) {
        Specification<WorkDetail> spec = where(null);

        if (request.getName() != null) spec = spec.and(name(request.getName()));
        if (request.getPhone() != null) spec = spec.and(phoneOne(request.getPhone()));
        if (request.getEmail() != null) spec = spec.and(email(request.getName()));
        if (request.getCompetences() != null) spec = spec.and(competences(request.getCompetences()));
        if (request.getRoles() != null) spec = spec.and(roles(request.getRoles()));
        if (request.getStatus() != null) spec = spec.and(status(request.getStatus()));

        return workDetailRepository.findAll(spec, pageable);
    }

这是我当前正在使用的规范。

public static Specification<WorkDetail> competences(String competences){
    return (root, query, criteriaBuilder) -> criteriaBuilder.equal(root.get("competences").get("name"), competences);
}

这个想法是使用来自说的参数:

http://localhost:8080/workers?competences=A&competences=B&competences=C

应用程序将找到所有具有A,B和C能力的工人

现在,我收到此错误:Illegal attempt to dereference path source [null.competences] of basic type;,但我还是没有正确执行此操作。有人做过吗?

能力和工作细节之间存在多对多的关系

1 个答案:

答案 0 :(得分:0)

如果您想在查询中允许多个能力,则getCompetences()应该返回一个List<String>

您的能力方法还应该具有相同的参数类型,并且在创建条件时应使用equal来代替in