So, I've got a Spring Application that saves books and authors. Author has Long id, String name. Book has Long id, String name and object of class Author author. In JSON it has to be like
{
"name": "Rich dad",
"authorDto": {
"id":2
}
}
So When I try to send the GET request for bookList I've got next message of error:
Cannot invoke "kg.istschool.bookservice.model.entity.Author.getId()" because "author" is null
at kg.istschool.bookservice.mappers.AuthorMapper.authorToAuthorDto(AuthorMapper.java:27) ~[classes/:na]
at kg.istschool.bookservice.mappers.BookMapper.bookToBookDto(BookMapper.java:45) ~[classes/:na]
Here is the link for the project: https://github.com/uli2912/book-service
The Idea shows me that problem is in here
public AuthorDto authorToAuthorDto(Author author) {
AuthorDto authorDto = new AuthorDto();
authorDto.setId(author.getId());
authorDto.setName(author.getName());
return authorDto;
}
@Override
public List<BookDTO> getBooks() {
List<Book> bookList = bookRepo.findAll();
List<BookDTO> bookDTOList = bookList.stream()
.map(x -> bookMapper.bookToBookDto(x))
.collect(Collectors.toList());
return bookDTOList;
}
public BookDTO bookToBookDto(@RequestBody Book book) {
if (Objects.isNull(book)) {
return null;
}
BookDTO bookDTO = new BookDTO();
bookDTO.setId(book.getId());
bookDTO.setName(book.getName());
bookDTO.setAuthorDto(authorMapper.authorToAuthorDto(book.getAuthor()));
return bookDTO;
}
So what's wrong there?