@RequestParam不需要时仍为null

时间:2018-07-05 10:13:20

标签: spring spring-data spring-rest

我的控制器具有一个参数:

@GetMapping("/people")
    public Page<People> list(
            @RequestParam(name="name", required = false) String name
            Pageable pageable
            ){

        Page<People> peoples=PeopleService.findByName(pageable,name);
        return peoples;

    }

我去localhost:8080/people?name=John时给我正确的数据,但是当我去localhost:8080/people时给我没有数据,但我想给我所有人。

我发现它是由Spring引起的,它仍在搜索where name=null

由于我有更多参数,例如年龄,日期等,如何解决此问题?

2 个答案:

答案 0 :(得分:0)

您正在使用不需要的findByName参数调用方法name。检查name变量是否为空,并取决于该调用findByNamefindAll方法。

@GetMapping("/people")
    public Page<People> list(
            @RequestParam(name="name", required = false) String name
            Pageable pageable
            ){
        if(name != null){

        Page<People> peoples=PeopleService.findByName(pageable,name);
        return peoples;

        }else{

        Page<People> peoples=PeopleService.findAll(pageable);
        return peoples;

        }

    }

答案 1 :(得分:0)

您可以在Spring Data中使用Specifications

只需使您的PeopleService接口(如果它是您的spring数据存储库接口)扩展JpaSpecificationExecutor< People >并创建一个像PeopleSpecification这样的类,就可以像这样实现Specification< People >

public class PeopleSpecification implements Specification<People> {

    private String firstName;

    //getters and setters

    public Predicate toPredicate(Root<People> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
        if (firstName != null)
            return cb.equal(root.get("firstName"), firstName);
        return cb.and();
    }
}

然后更改您的控制器方法以获取PeopleSpecification的实例作为参数:

public Page<People> list(@ModelAttribute PeopleSpecification specification, Pagable pageable)

最后在控制器的JpaSpecificationExecutor中使用从PeopleService继承的新方法:

Page<People> findAll(Specification<People> specification, Pageable pageable);

很明显,您可以更改PeopleSpefication类的实现,使其具有所需的任意数量的属性,并更改toPredicate方法逻辑以返回正确的谓词对象。