如何使用Spring以一种安静的方式过滤数据?

Daw*_*wid 13 java rest spring hibernate filter

正如标题所说.

我基本上会喜欢这样的请求

/api/todos/?completed=eq.true&created_at=lt.1486462109399
Run Code Online (Sandbox Code Playgroud)

有没有准备好spring way实现这样的?类似于Page/Pageable机制的东西会很棒.

如果没有,我想我可以使用Hibernate Criteria Queries&Argument Re-solvers来实现它.基本上允许我写我的控制器像

 @GetMapping
 public ResponseEntity<Page<TodoDTO>> listAll(Criteria criteria, Pageable pageable) 
 {
        Page<Todo> todos = todoService.listAll(criteria, pageable)
        ...
 }
Run Code Online (Sandbox Code Playgroud)

自定义参数解析器将负责将查询字符串转换为条件.我还不确定如何在服务中处理它,但这是我试图实现它的方向.

这会是一个好方法吗?有什么建议?(所有假设已经没有现成的机制).

非常感谢您的帮助.

naX*_*aXa 5

您可以使用Spring Data JPA和Specification来构建Search / Filter REST API。这是结果API可以处理的测试URL示例:

http://localhost:8080/users?search=lastName:doe,age>25
Run Code Online (Sandbox Code Playgroud)

和示例控制器:

@RestController
@RequestMapping(value = "/users")
public class UserController {

    @Autowired
    private UserRepository repo;

    @GetMapping
    public List<User> search(@RequestParam(value = "search") String search) {
        UserSpecificationsBuilder builder = new UserSpecificationsBuilder();
        Pattern pattern = Pattern.compile("(\w+?)(:|<|>)(\w+?),");
        Matcher matcher = pattern.matcher(search + ",");
        while (matcher.find()) {
            builder.with(matcher.group(1), matcher.group(2), matcher.group(3));
        }

        Specification<User> spec = builder.build();
        return repo.findAll(spec);
    }
}
Run Code Online (Sandbox Code Playgroud)


naX*_*aXa 5

构建流畅的查询API的另一种方法是使用RSQL解析器。RSQL是一种用于对RESTful API中的条目进行参数化过滤的查询语言。遵循本文,您的API将能够处理以下网址:

http://localhost:8080/users?search=firstName==jo*;age<25
Run Code Online (Sandbox Code Playgroud)

样品控制器:

@RestController
@RequestMapping(value = "/users")
public class UserController {

    @Autowired
    private UserRepository repo;

    @GetMapping
    public List<User> findAllByRsql(@RequestParam(value = "search") String search) {
        Node rootNode = new RSQLParser().parse(search);
        Specification<User> spec = rootNode.accept(new CustomRsqlVisitor<User>());
        return repo.findAll(spec);
    }

}
Run Code Online (Sandbox Code Playgroud)