遇到的问题
使用JPA findBy语句查询MySQL返回结果为空时,返回Result must not be null!500错误。
解决方法
最后在官方文档中查到对于Repository中的方法需要专门处理结果为空时的情况。若使结果可为空,需要在方法前加@Nullable
注解。
只需将
interface UserRepository: JpaRepository<User, Long> {
fun findByUsername(username: String): User
}
改为
import org.springframework.lang.Nullable
interface UserRepository: JpaRepository<User, Long> {
@Nullable
fun findByUsername(username: String): User
}
即可解决。
注意,需要引入的包是
import org.springframework.lang.Nullable