Spring boot 按URL上的字段分页和排序存储库筛选器

Spring boot 按URL上的字段分页和排序存储库筛选器,spring-boot,spring-data-jpa,Spring Boot,Spring Data Jpa,请问是否可以通过URL上的字段过滤Spring启动实体?例如,我有一个名为Employee的类,其中包含字段first name和last name。我想按姓氏过滤。我第一次尝试的是:localhost:8080/api/employees?lastName=aaa,但结果是数据库中的所有条目 然后我在这篇文章中接受了这个答案:但它也不起作用 这是我的密码: public interface EmployeeRepository extends PagingAndSortingRepositor

请问是否可以通过URL上的字段过滤Spring启动实体?例如,我有一个名为Employee的类,其中包含字段first name和last name。我想按姓氏过滤。我第一次尝试的是:localhost:8080/api/employees?lastName=aaa,但结果是数据库中的所有条目

然后我在这篇文章中接受了这个答案:但它也不起作用

这是我的密码:

public interface EmployeeRepository extends PagingAndSortingRepository<Employee, Long> {

Page<Employee> findAllByLastName(String lastName, Pageable pageable);
结果

{
"cause": {
    "cause": null,
    "message": "For input string: \"lastName&page=0&size=2\""
},
"message": "Failed to convert from type [java.lang.String] to type [java.lang.Long] for value 'lastName&page=0&size=2'; nested exception is java.lang.NumberFormatException: For input string: \"lastName&page=0&size=2\""

}

Spring数据中的自定义搜索功能JPA REST结束于
search/
下。试试下面的方法

localhost:8080/api/employees/search/findAllByLastName?lastName=Sadakath&page=0&size=2

请尝试以下代码片段

@GetMapping("/api/search")
    public ResponseEntity<List<User>> serachUsers(@RequestParam("lastName") String lastName, Pageable pageable) {
        List<User> users = userRepository.findByLastNameContaining(lastName, pageable);
        return ResponseEntity.ok(users);
}

您可以使用零代码创建灵活的搜索,如上面提到的答案中所述。下面的两个答案要求为搜索参数的每个组合添加查询方法(可能还有控制器端点),这显然不是最优的。如果您使用的是SpringDataRESTExtension(您可能已经标记了它,但还没有标记它),那么基本相同,但显然没有MVC端点。
@GetMapping("/api/search")
    public ResponseEntity<List<User>> serachUsers(@RequestParam("lastName") String lastName, Pageable pageable) {
        List<User> users = userRepository.findByLastNameContaining(lastName, pageable);
        return ResponseEntity.ok(users);
}
@Repository
public interface UserRepository extends JpaRepository<User, Long> {

    List<User> findByLastNameContaining(String lastName, Pageable pageable);
}
curl --location --request GET 'http://localhost:8080/api/search?lastName=test&page=0&size=2'