使用列表/设置进行Spring Boot数据过滤

时间:2019-02-22 06:33:37

标签: java spring-boot

我有一个显示姓名,电子邮件等的表格,但也列出了某些用户所扮演的角色或能力。

我在使用例如角色数组过滤表时遇到麻烦。一个用户可以担任多个角色,该表显示了这一点。我需要能够通过选择两个角色来进行过滤:“服务管理器”和“物流管理器”。服务器响应应该是所有具有那些角色的用户。

用于过滤用户的控制器功能:

@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) Set<Competence> competences,
            @RequestParam(required = false) Set<UserRole> roles,
            @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> roles(Set<UserRole> roles) {
        return (root, query, criteriaBuilder) -> criteriaBuilder.equal(root.get("user").get("roles"), roles);
    }

当前,当我从前端发送角色对象时,它以字符串形式发送它们,而Spring Boot引发错误 Failed to convert value of type 'java.Lang.String' to required type 'java.util.Set'

1 个答案:

答案 0 :(得分:0)

您尝试创建

之类的查询
  

从角色等于'a','b','c'的表中选择*

这是无效的查询。

用于解决您的问题

criteriaBuilder.in(root.get("user").get("roles"), roles)