Now, the single findOne() method that you will find in CrudRepository is the one defined in the QueryByExampleExecutor interface as:<S extends T> Optional<S> findOne(Example<S> example);最后由SimpleJpaRepository实现,CrudRepository接口的默认实现.此方法是按示例搜索查询,您不希望将其作为替代.That is implemented finally by SimpleJpaRepository, the default implementation of the CrudRepository interface.This method is a query by example search and you don't want that as a replacement.其实在新的API中,行为相同的方法还是有的,只是方法名变了.它在 findOne() 重命名为 findById()current/api/org/springframework/data/repository/CrudRepository.html" rel="noreferrer">CrudRepository 接口:In fact, the method with the same behavior is still there in the new API, but the method name has changed.It was renamed from findOne() to findById() in the CrudRepository interface :Optional<T> findById(ID id); 现在它返回一个Optional,这对于防止NullPointerException来说还不错.Now it returns an Optional, which is not so bad to prevent NullPointerException.所以,实际调用的方法现在是 Optional;findById(ID id).如何使用?学习可选用法.以下是有关其规范的重要信息:How to use that?Learning Optional usage.Here's important information about its specification:可能包含也可能不包含非空值的容器对象.如果一个value 存在,isPresent() 将返回 true 并且 get() 将返回价值.依赖于存在或不存在的其他方法提供了包含的值,例如 orElse()(返回默认值如果值不存在)和 ifPresent()(如果值存在).Additional methods that depend on the presence or absence of acontained value are provided, such as orElse() (return a default valueif value not present) and ifPresent() (execute a block of code if thevalue is present).关于如何使用 Optional 和 Optional 的一些提示;findById(ID id).Some hints on how to use Optional with Optional<T> findById(ID id).通常,当您通过 id 查找实体时,您希望将其返回或在未检索到的情况下进行特定处理.Generally, as you look for an entity by id, you want to return it or make a particular processing if that is not retrieved.以下是三个经典用法示例.Here are three classical usage examples.假设如果找到实体,您想要获取它,否则您想要获取默认值.你可以写:Foo foo = repository.findById(id) .orElse(new Foo());或者在有意义的情况下获取 null 默认值(与 API 更改之前的行为相同):or get a null default value if it makes sense (same behavior as before the API change) :Foo foo = repository.findById(id) .orElse(null);假设如果找到实体,您想返回它,否则您想抛出异常.你可以写:return repository.findById(id) .orElseThrow(() -> new EntityNotFoundException(id));假设您想根据是否找到实体来应用不同的处理(不必抛出异常).你可以写:Optional<Foo> fooOptional = fooRepository.findById(id);if (fooOptional.isPresent()) { Foo foo = fooOptional.get(); // processing with foo ...} else { // alternative processing....} 这篇关于Spring Data JPA findOne() 更改为 Optional 如何使用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 10-22 10:33