Good time of the day, I faced a problem with a null pointer exception
In the project, I have a Service class where my Repository is injected. I have my entity Book. In service, I am trying to find a book by a slug of the book via the method of the repository. The repository works well and gives me right object, but I don't know why, if I log any information about that object, it first logs correctly, but after that, it throws a null pointer exception. Program works good but the exception annoying I hope I can explain the problem
@Repository
public interface BookRepository extends JpaRepository<Book, Integer> {
@Query("select b from Book b where b.slug = ?1")
Book findBookBySlug(String book);
}
@Service
@Slf4j
public class BookServiceImpl implements BookService {
public final BookRepository bookRepository;
public BookServiceImpl(BookRepository bookRepository) {
this.bookRepository = bookRepository;
}
@Override
public Book getBookBySlug(String slug) {
log.info("image source: " + bookRepository.findBookBySlug(slug).getImage());
return bookRepository.findBookBySlug(slug);
}
}
@GetMapping("/{slug}")
public String getBookPage(@PathVariable String slug, Model model) {
Book bookToReturn = bookService.getBookBySlug(slug);
model.addAttribute("slugBook", bookToReturn);
return "books/slug";
}
Cannot invoke "com.bekzodkeldiyarov.bookshop.model.Book.getImage()" because the return value of "com.bekzodkeldiyarov.bookshop.repository.BookRepository.findBookBySlug(String)" is null

