1

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

@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中。

由于我有更多的参数,如年龄、日期等,如何解决这个问题?

4

2 回答 2

0

您正在使用不需要findByName的参数调用方法。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;

        }

    }
于 2018-07-05T11:02:38.163 回答
0

您可以SpecificationsSpring Data.

只需让你的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方法逻辑以返回正确的 Predicate 对象。

于 2018-07-08T11:42:21.610 回答