Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/378.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 可选OrelsThrow提供空指针异常_Java_Nullpointerexception_Optional - Fatal编程技术网

Java 可选OrelsThrow提供空指针异常

Java 可选OrelsThrow提供空指针异常,java,nullpointerexception,optional,Java,Nullpointerexception,Optional,我有这个方法: public Tenant getTenant(String tenantId) throws TenantNotFoundException { return tenantDatabaseService.findTenantById(tenantId) .orElseThrow(() -> new TenantNotFoundException("Tenant not found")); } tenantDatabaseService.FindTenantByd

我有这个方法:

public Tenant getTenant(String tenantId) throws TenantNotFoundException {
return tenantDatabaseService.findTenantById(tenantId)
    .orElseThrow(() -> new TenantNotFoundException("Tenant not found"));
}
tenantDatabaseService.FindTenantBydTenantId返回一个可选的:

这里有什么帮助吗?

如果您的意思是tenantepository.findByIdid有时返回null,我将按照以下方式调整它

public Optional<Tenant> findTenantById(String id) {
    return Optional.ofNullable(tenantRepository.findById(id));
}

myyjpa实现有一个问题,链中的一个方法抛出null,正如你们中的许多人所提到的。感谢您的帮助。

链中的一个方法返回null而不是可选的。请添加异常的堆栈跟踪。新的nullpointerexception描述消息非常明显:findTenantById返回null而不是空选项RepositoryfindById的声明是什么?@ernest\k I删除它,因为如果findById未声明为返回可选值,则会导致编译错误,因此findTenantById将返回可选值。。。还是我遗漏了什么?
Failed to complete request: java.lang.NullPointerException: while trying to invoke the method 
java.util.Optional.orElseThrow(java.util.function.Supplier) of a null object returned from 
com.sap.gb.service.TenantDatabaseService.findTenantById(java.lang.String)
public Optional<Tenant> findTenantById(String id) {
    return Optional.ofNullable(tenantRepository.findById(id));
}