'How to set required=false on a (int or boolean) @RequestParam without default value?
I need a rest get method that search books by multiple optional parameters. This is the method:
@GetMapping("/all")
public ResponseEntity<Optional<List<Book>>> findByAll(@RequestParam(value = "title") String title,
@RequestParam(value = "author") String author, @RequestParam(value = "new", required = false) boolean new,
@RequestParam(value = "category", required = false) int category) {
Optional<List<Book>> bookList = booksService.findByAll(title, author, new, category);
return new ResponseEntity<Optional<List<Book>>>(bookList, HttpStatus.OK);
}
all of theese parameters should be optional. For example, if all input are empty should return all the books from db. required=false needs a defaultvalue but i cannot set a default value for new and category.
Solution 1:[1]
You can't make a primitive type optional, because that implies/requires nullability, and a primitive cannot be null - only an object reference can be null.
So, you can change the int to an Integer, and that can then be optional.
Solution 2:[2]
It is impossible because it proceeds procedurally.
Instead, use @RequestBody and Deserializable object to get search value.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | GreyBeardedGeek |
| Solution 2 | seleveal |
