Sobes.tech
Senior

@PutMapping("/create") public Book create(@RequestBody CreateBook request) throws Exception { System.out.println("Check if book exists " + map); Book book = new ObjectMapper().convertValue(map, Book.class); Book b = repo.findByTitle(book.getTitle()); if (b != null) { throw new Exception("Book already exists"); } book.setId(UUID.randomUUID().toString()); repo.save(book); log.debug("Book {} by {} is created with id {}", book.getTitle(), book.getAuthor(), book.getId()); return book; } @GetMapping("/get") public Book get(@QueryParam("id") String id) { log.debug("Get book " + id); return repo.findAll().stream() .filter(b -> b.getId().equals(id)) .findFirst().get(); } @GetMapping("/{id}") public Book get(@RequestParam("id") String id) { log.debug("Get book ", id); return repo.findById(id).orElseThrow(() -> new BookAlreadyExeption("book not find")) findAll().stream() .filter(b -> b.getId().equals(id)) .findFirst().get(); }

sobes.tech AI

Answer from AI

The provided code has several issues and inaccuracies:

  1. In the create method, the variable map is used, which is not defined in the method — it should probably be the request parameter.
  2. The get methods use different annotations for parameters (@QueryParam and @RequestParam), which can lead to conflicts. In Spring MVC, typically @RequestParam or @PathVariable are used.
  3. In the last get method, there is a syntax error: after orElseThrow, there is unnecessary code findAll().stream()..., which makes no sense.
  4. The exception BookAlreadyExeption is misspelled (it should be BookAlreadyException).

Here is a corrected example of the create book method:

@PostMapping("/create")
public Book create(@RequestBody CreateBook request) throws Exception {
    Book book = new ObjectMapper().convertValue(request, Book.class);
    Book existing = repo.findByTitle(book.getTitle());
    if (existing != null) {
        throw new Exception("Book already exists");
    }
    book.setId(UUID.randomUUID().toString());
    repo.save(book);
    log.debug("Book {} by {} is created with id {}", book.getTitle(), book.getAuthor(), book.getId());
    return book;
}

And an example of the method to get a book by id:

@GetMapping("/{id}")
public Book get(@PathVariable String id) {
    log.debug("Get book {}", id);
    return repo.findById(id).orElseThrow(() -> new BookNotFoundException("Book not found"));
}

Thus, it is important to pay close attention to the correctness of annotations, exception handling, and parameter usage.