Home > Enterprise >  How to set required=false on a (int or boolean) @RequestParam without default value?
How to set required=false on a (int or boolean) @RequestParam without default value?

Time:02-24

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.

CodePudding user response:

It is impossible because it proceeds procedurally.

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

CodePudding user response:

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.

  • Related