Problems encountered when Spring Data JPA query result is empty

2019-05-26
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.

Solution

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);

}

To

interface UserRepository extends Repository <User, Long> {

     @Nullable
     User findByName (String name);

}

That’s it.

This post was originally published on my personal blog wangchucheng.com.
Original link: https://wangchucheng.com/en/posts/empty-result-in-spring-data-jpa/
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.

Avatar

WANG Chucheng

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