Sobes.tech
Senior

@PutMapping("/create") public Book create(Map<String, Object> map) 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(); }

sobes.tech AI

Answer from AI

The provided code has several important points:

  1. The create method uses Map<String, Object> to accept data, which is not typical for Spring MVC. Usually, a DTO with the @RequestBody annotation is used.

  2. The existence of a book by title is checked via repo.findByTitle. If the book is found, an exception is thrown.

  3. For ID creation, UUID.randomUUID().toString() is used.

  4. In the get method, @QueryParam (from JAX-RS) is used, but in Spring MVC, it is more correct to use @RequestParam.

  5. Searching for a book by ID is done by iterating over all records with repo.findAll(), which is inefficient. It is better to use the repository method findById.

An improved example:

@PostMapping("/create")
public Book create(@RequestBody Book book) throws Exception {
    if (repo.findByTitle(book.getTitle()) != 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(@RequestParam("id") String id) {
    log.debug("Get book {}", id);
    return repo.findById(id).orElse(null);
}

This approach is more typical and efficient for Spring Boot applications.

@PutMapping("/create") public Book create(Map<String… - sobes.tech