Answer the question
In order to leave comments, you need to log in
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);
}
class User {
int id;
String name;
int height;
int weight;
}
public interface UserRepository extends CrudRepository<User, Integer> {
}
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);
}
Answer the question
In order to leave comments, you need to log in
Look here .
You will need to add the Querydsl library to the project dependencies.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question