How to filter data using Spring?

As the name says.

Basically I would like to make queries like

/api/todos/?completed=eq.true&created_at=lt.1486462109399 

Are there any ready-made spring way to achieve this? Something similar to the page / page mechanism would be great.

If not, I think I could implement it using the Hibernate Criteria Queries and Argument Re-solvers. Basically allows me to write my controllers, for example

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

The Argument custom argument is responsible for turning the query string into criteria. Not quite sure how I would handle this in the service, but in the direction in which I would try to implement this.

Would this be a good approach? Any recommendations? (Everyone suggests that there is no ready-made mechanism for this).

Your help is greatly appreciated.

+6
source share
2 answers

Another option for creating a free API query is to use the RSQL parser. RSQL is a query language for parameterized filtering of records in the RESTful API. Follow this article and your API will be able to handle URLs, for example:

 http://localhost:8080/users?search=firstName==jo*;age<25 

Sample Controller:

 @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); } } 
+1
source

You can create a REST Search / Filter API using Spring JPA data and specifications . The following is an example of a test URL that can process the resulting API:

 http://localhost:8080/users?search=lastName:doe,age>25 

and an example controller:

 @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); } } 
0
source

Source: https://habr.com/ru/post/1014761/


All Articles