英文:
Java Spring Boot - MongoDB findById compilation error
问题
我在我的Service文件中有以下方法:
public MappingModel getById(String id) {
return repository.findById(id);
}
这是我的repository:
public interface MappingRepository extends MongoRepository<MappingModel, String> {
List<MappingModel> findByProject(String project);
}
在编译时,我得到了以下错误:
不兼容的类型:
java.util.Optional<com.xxx.xxx.xxx.model.MappingModel>无法转换为com.xxx.xxx.xxx.model.MappingModel
我应该从我的Service返回什么类型?难道不应该是Model本身(我当前正在尝试返回的内容)吗?
谢谢
英文:
I've got the following method in my Service file:
public MappingModel getById(String id) {
return repository.findById(id);
}
and this is my repository:
public interface MappingRepository extends MongoRepository<MappingModel, String> {
List<MappingModel> findByProject(String project);
}
while compiling I'm getting the following error:
> incompatible types:
> java.util.Optional<com.xxx.xxx.xxx.model.MappingModel> cannot be
> converted to com.xxx.xxx.xxx.model.MappingModel
What type should I be returning from my Service? shouldn't be the Model itself (what I'm currently trying to return)?
Thanks
答案1
得分: 3
你应该返回的类型在错误信息中。findById() 返回一个 Optional<MappingModel>
,所以你可以要么将你的服务的返回类型改为 Optional<MappingModel>
,要么在服务中处理这个 Optional。
编辑以为提问者提供关于 Optionals 的更多信息:
作为一个程序员,你可能已经遇到过无数次可怕的空指针异常。Java 的一个大问题是,当你看一个参数时,很难确定它是否可能为 null,或者是否确保它一定存在,所以通常情况下你的整个代码库到处都是空值检查(尤其是在嵌套对象中,这种情况尤其严重)。
Optionals 是一种明确表示,这个对象有可能为 null,你需要以某种方式来处理它。这可能看起来是一件小事,但实际上基于几个原因,它非常强大。
-
如果你在代码库中始终在使用 Optionals,那么你可以基本上消除可怕的空指针检查。如果在某种情况下对象可能为空,你总是使用 Optional,那么你就在暗示所有不是 Optional 的东西都不是 null,所以任何空指针异常都是你的代码中的逻辑错误(你知道需要修复它们)。
-
Optionals 在流式 API 中表现得非常好。这是一个太大的主题,在这里无法详细介绍,但基本上,许多程序流程都相当简单。如果我们有这个项目,我们尝试对它进行一系列的操作,但如果没有,那么我们就不进行操作或抛出异常。试一试,你在这之后会更加欣赏 Optionals。我认为它能够带来非常可读的代码。
-
许多包支持 Optionals,因此它们可能会为你处理它们。例如,如果这个对象存在,我们将其作为 JSON 响应的一部分返回。否则,我们将忽略它。
从用例的角度来看,想象一下使用集合(比如列表)的感觉。我们通常期望列表永远不会为 null,只会是空的,所以使用它们会很舒服。Optionals 在某种程度上就像是这个概念的扩展(而且流式 API 的许多方法都重载了以处理集合和 Optionals)。
英文:
The type that you’re supposed to be returning is in the error message . findById() returns an Optional<MappingModel>
, so you can either change the return type of your service to Optional<MappingModel>
or you can handle the Optional in the service.
https://docs.oracle.com/javase/8/docs/api/java/util/Optional.html
Edit to provide questioner more information about Optionals:
As a programmer, you've probably had faced the dreaded NullPointerException thousands of times. A big problem with Java is that when you look at a parameter, it's really hard to tell if it can be null or if it's guaranteed to be there, so what usually ends up happening is that your entire code base is filled with null checks (this is especially bad with nested objects).
Optionals are a way of explicitly saying, this object has a possibility that it's null, you need to account for that in some way. This might seem like a small thing, but it's actually very powerful for several reasons.
-
If you're consistent with your use of Optionals in your code base, then you can mostly eliminate the dreaded null-check. If you always use an optional when something could be null, then you are implying that everything that is not an optional, is not null, so any nullpointers that you get are a result of a logical error in your code (which you know that you need to fix).
-
Optionals work really well with the stream API. This is too big a topic to cover here, but basically, many program flows are quite simple. If we have the item, we attempt to do a sequence of operations to it, but if it's not, then we don't or throw an exception. Try it out, you'll appreciate Optionals a lot more after you do. I think it leads to really readable code.
-
Many packages support Optionals, so they might handle them for you. For example, if this object is present, then we will return it as part of a JSON response. Otherwise, we'll ignore it.
From a use-case perspective, think about what it feels like to work with Collections like Lists. We usually expect that the List is never null, just empty, so using them just feels nice. Optionals are somewhat like an extension of this (and many of the stream API methods are overloaded to handle both Collections and Optionals).
答案2
得分: 1
以下是翻译好的部分:
当您使用MongoRepository
的findById()
方法时,它会给您一个Optional<>
类型,这意味着数据可以存在于数据库中,也可以不存在。因此,按照以下方式更改类型:
public Optional<MappingModel> getById(String id) {
return repository.findById(id);
}
当您在服务实现中使用此方法时,您需要这样做:
public MappingModel getById(String id){
if(repository.getById(id).isPresent())
{
MappingModel m= repository.getById(id).get();
// 然后是您的常规逻辑
return m;
}
throw new RuntimeException("数据未找到");
}
英文:
When you use findById()
of MongoRepository, it will give you an Optional<>
type which means, that data either can be present in the database or not. So change the type like following
public Optional<MappingModel> getById(String id) {
return repository.findById(id);
}
When you use this method in service implementation, you need to use,
public MappingModel getById(String id){
if(repository.getById(id).isPresent())
{
MappingModel m= repository.getById(id).get();
// then your usual logic
return m;
}
throw new RuntimeException("Data not found");
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论