0

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.

  • You cannot, those are primitives and always have a default value. Don't use primitives but the object wrapper if they are conditional. – M. Deinum Feb 24 '22 at 13:18

2 Answers2

2

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.

GreyBeardedGeek
  • 29,460
  • 2
  • 47
  • 67
-1

It is impossible because it proceeds procedurally.

Instead, use @RequestBody and Deserializable object to get search value.

seleveal
  • 32
  • 4