1

Could you please help me and explain how should I pass an author value?

@GetMapping(value = "/search")
    public ResponseEntity<List<Book>> searchBooksByTitleAndAuthor(
            @RequestParam(value = "title", required = false) final String title,
            @RequestParam(value = "author", required = false) final Author author) {
        HttpStatus httpStatus = HttpStatus.OK;
        List<Book> books = null;
        if (title == null && author == null) {
            log.info("Empty request");
            httpStatus = HttpStatus.BAD_REQUEST;
        } else if (title == null || author == null) {
            books = bookService.getBooksByTitleOrAuthor(title, author);
        } else {
            Optional<Book> book = bookService.getBookByTitleAndAuthor(title, author);
            if (book.isPresent()) {
                books = Arrays.asList(book.get());
            }
        }
        if (books == null) {
            return new ResponseEntity<>(httpStatus);
        } else {
            return new ResponseEntity<>(books, httpStatus);
        }
    }

And Author class that looks like:

@Entity
@NoArgsConstructor
@AllArgsConstructor
@Getter
@EqualsAndHashCode
@ToString
public final class Author {

    @Id
    @GeneratedValue(strategy=GenerationType.IDENTITY)
    private Long id;

    private String name;

    private LocalDate dateOfBirth;

    private String bio;
}

Is it a good approach to use author or @RequestParam instead of request body in this situation? I've thought about requesting only String that is authors' name but it will affect service's methods.

Pasha
  • 1,768
  • 6
  • 22
  • 43

1 Answers1

2

According to https://lankydanblog.com/2017/03/11/passing-data-transfer-objects-with-get-in-spring-boot/ , ... you can (after you set some conversion annotations on your author.dateOfBirth):

  1. Use @RequestParam on a String parameter (and let your controller/someone do the conversion):

        ..., @RequestParam(value = "author", required = false) final String author) { 
    
         ...final Author author = new ObjectMapper().setDateFormat(simpleDateFormat)
                                 .readValue(author, Author.class);
    

    In this case you would request like:

    http://localhost:8080/myApp/search?title=foo&author={"id"="1",...}
    
  2. alternatively: Omit @RequestParam, but pass the object (and let spring care for conversion):

    ...(@RequestParam(value = "title", required = false) final String title,
         final Author author)
    

    and request like:

    http://localhost:8080/myApp/search?title=foo&id=1&name=Donald E. Knuth&...
    

See also:

xerx593
  • 12,237
  • 5
  • 33
  • 64