Problems encountered when spring data JPA query result is null

Time:2020-12-3

Problems encountered

When using the repository interface, a null pointer exception will be reported if the query result of findby method is nulljava.lang.NullPointerExceptionWhen the query result is not empty, it can pass the test.

This article first appeared in my personal blog technology mansion( wcc.im )Problems encountered when spring data JPA query result is null

resolvent

Most of the reasons for using repository null pointer exception found on the Internet are injection problems, which are not used@Autowired, but that doesn’t apply to the problem I’m having.

After determining the location, I found that my error report appears in the findby method. Finally, it is found in the official document that the method in the repository needs to handle the case when the result is empty. If the result can be empty, you need to add before the method@NullableNotes.

So just put

interface UserRepository extends Repository<User, Long> {                 

    User findByName(String name);

}

Change to

interface UserRepository extends Repository<User, Long> {                 

    @Nullable
    User findByName(String name);

}

That’s fine.

This article first appeared in my personal blog technology mansion( wcc.im )。
Link to the original text: https://wcc.im/zh/post/empty-result-in-spring-data-jpa/
All articles in this blog are original, and are licensed by CC by-nc-sa 4.0 license agreement. For use beyond the CC by-nc-sa 4.0 license agreement, please contact the author for authorization.

Recommended Today

SQL server cannot generate fruncm thread

SQL Server was unable to generate the fruncm thread. The database error log is as follows: Copy codeThe code is as follows: 2013-09-26 21:21:50.31 Server      Microsoft SQL Server 2005 – 9.00.1399.06 (Intel X86)Oct 14 2005 00:33:37 Copyright (c) 1988-2005 Microsoft CorporationEnterprise Edition on Windows NT 5.2 (Build 3790: Service Pack 2) 2013-09-26 21:21:50.31 Server      (c) […]