Home > database >  Return an item by id
Return an item by id

Time:11-25

I got this piece of code, I am learning from tutorial. I want to return an element by url which looks like clients/1 instead of clients?id=1. How can I achieve this? Also, can the code below be made easier way?

    @GetMapping
    public Client getClient(@RequestParam int id) {
        Optional<Client> first = clientList.stream().filter(element -> element.getId() == id).findFirst();
        return first.get();
    }

CodePudding user response:

You may want to use @PathVariable as follows:

@Controller
@RequestMapping("/clients")
public class MyController {

    @GetMapping("/{id}")
    public Client getClient(@PathVariable int id) {
        return clientList.stream().filter(element -> element.getId() == id).findFirst().orElseThrow();
    }

Please note, the Optional can be unpacked with orElseThrow method. This will throw a NoSuchElementException in case there is no element found for the id.

Other solution would be to use orElse(new Client(...)) to return a default value if nothing is found.

get() is not really recommended to be used. From the JavaDoc of the get() method:

API Note: The preferred alternative to this method is orElseThrow().

Even though get() may also throw a NoSuchElementException, similar to orElseThrow, usually the consensus is that get should not be used without isPresent, or should not be used at all. There several other methods to unpack the Optional without forcing you write an if.

The whole idea of the Optional is to overcome this by forcing you to think about the case when there is no value inside.

  • Related