Problems encountered when Spring Data JPA query result is empty

2 min read

Problems encountered

When using the Repository interface, if the query result of the findBy method is empty, a null pointer exception java.lang.NullPointerException will be reported, and if the query result is not empty, you can pass the test.

This article was originally written in Chinese and translated into English by a translation software without proofreading. So please understand the possible inaccuracies and rigor in the article.


The reasons for using the Repository to report null pointer exceptions found on the Internet are mostly due to injection problems. @Autowired is not used, but this does not apply to the problem I encountered.

After determining the location, I found that my error appeared in the findBy method. Finally, I found in the official document that the method in the Repository needs to be specially processed and the result is empty Situation. If the result is nullable, you need to add the @Nullable annotation before the method.

So just change

interface UserRepository extends Repository <User, Long> {

     User findByName (String name);



interface UserRepository extends Repository <User, Long> {

     User findByName (String name);


That’s it.

This post was originally published on my personal blog
Original link:
Posts in this blog are original unless otherwise stated, and are licensed under a CC BY-NC-SA 4.0 License. Use beyond the lincense please contact the author for authorization.


WANG Chucheng

He is an authentic Tianjin native, but not proficient in any of the four classic skills in Xiangsheng (Speaking, Imitating, Teasing, Singing).