@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:
-
The
createmethod usesMap<String, Object>to accept data, which is not typical for Spring MVC. Usually, a DTO with the@RequestBodyannotation is used. -
The existence of a book by title is checked via
repo.findByTitle. If the book is found, an exception is thrown. -
For ID creation,
UUID.randomUUID().toString()is used. -
In the
getmethod,@QueryParam(from JAX-RS) is used, but in Spring MVC, it is more correct to use@RequestParam. -
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 methodfindById.
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.