-1

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?

2 Answers2

2

The problem is in 'Author' entity. The error trace indicates that Author is null.

Cannot invoke "kg.istschool.bookservice.model.entity.Author.getId()" because "author" is null

You obtain 'Author' from repository, using findAll of your 'Book' entity.

'Book' entity should have a FK relation with 'Author' entity. Probably, in your 'Book' table in database, the column 'Author' is null, or the relationship is bad defined.

If you have access to database, I suggest you check the table 'Book' and find the value of related-column 'Author'. If this column can be nullable, you should control this in your code.

public AuthorDto authorToAuthorDto(Author author) {
if(author == null) return null;
//... your map
}
Talenel
  • 422
  • 2
  • 6
  • 25
0

For this project in database you have to add auto increment in field Id of author table. check this

enter image description here

check your database table! is it there! Why this much needed for ID you can put @ID and @GeneratedValue(strategy = GenerationType.AUTO)

Not need of this code @Id @GeneratedValue( strategy = GenerationType.SEQUENCE, generator = "author_seq" ) @SequenceGenerator( name = "authors_seq", sequenceName = "author_sequence", initialValue = 1, allocationSize = 50 )