A
A
Andrey Myvrenik2016-09-17 15:02:23
Java
Andrey Myvrenik, 2016-09-17 15:02:23

How to implement a filter by parameters in Spring for a RESTful service?

Let's say we have a REST service with a User collection:

@RequestMapping("/users")
public HttpEntity<List<User>> users() {
    // Достаём пользователей из БД
    List<User> users = userRepository.findAll();

    return new ResponseEntity<>(users, HttpStatus.OK);
}

Where User:
class User {
    int id;
    String name;
    int height;
    int weight;
}

And the repository's CRUD interface:
public interface UserRepository extends CrudRepository<User, Integer> {
}

How can I implement a filter so that when querying with the "height=180" parameter, only users whose height value in the database is 180 are displayed? You can, of course, do something like this:
public interface UserRepository extends CrudRepository<User, Integer> {
    @Query("FROM User WHERE height = :height")
    List<User> findAllByHeight(@Param("height") int height);
}

@RequestMapping("/users")
public HttpEntity<List<User>> users(
        @RequestParam(value = "height", required = false) Integer height) { // <- Опциональный параметр height

    // Достаём пользователей из БД
    if(height == null) // <- Некрасивые условия
        List<User> users = userRepository.findAll();
    else
        List<User> users = userRepository.findAllByHeight(height);

    return new ResponseEntity<>(users, HttpStatus.OK);
}

And it's not so scary, but what if you need to be able to filter by several parameters, including at the same time? Is there a more beautiful way to solve this problem in the Spring framework?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Artem Kileev, 2016-09-17
@gim0

Look here .
You will need to add the Querydsl library to the project dependencies.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question