Spring Data JPA的findOne()更改为Optional怎么使用? [英] Spring Data JPA findOne() change to Optional how to use this?

查看:1617
本文介绍了Spring Data JPA的findOne()更改为Optional怎么使用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在与Java8一起学习SpringBoot2.0.

然后我遵循了一些博客制作教程示例.

And I followed some blog-making tutorial example.

该教程的源代码为:

@GetMapping("/{id}/edit")
public String edit(@PathVariable Long id, Model model) {
  model.addAttribute("categoryDto", categoryService.findOne(id));
  return "category/edit";
}

但是此代码抛出此错误:

But this code is throwing this error:

categoryService.findOne(id)

categoryService.findOne(id)

我正在考虑将JPA findOne()方法更改为Optional< S >

I'm thinking about changing the JPA findOne() method to Optional< S >

如何解决?

更多信息:

这是categoryService方法:

This is the categoryService method:

public Category findOne(Long id) {
  return categoryRepository.findOne(id);
}

推荐答案

至少从2.0版本开始,Spring-Data-Jpa修改了findOne().
现在,findOne()没有相同的签名和相同的行为.
以前,它在CrudRepository界面中定义为:

From at least, the 2.0 version, Spring-Data-Jpa modified findOne().
Now, findOne() doesn't have both the same signature and the same behavior.
Previously, it was defined in the CrudRepository interface as :

T findOne(ID primaryKey);

现在,您将在CrudRepository中找到的单个findOne()方法是在QueryByExampleExecutor界面中定义为:

Now, the single findOne() method that you will find in CrudRepository is which one defined in the QueryByExampleExecutor interface as :

<S extends T> Optional<S> findOne(Example<S> example);

最终由CrudRepository接口的默认实现SimpleJpaRepository实现.
此方法是通过示例搜索查询的,您不想将其替换.

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 to that as replacement.

实际上,具有相同行为的方法仍在新API中,但是方法名称已更改.

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<T> findById(ID id).

So, the actual method to invoke is now Optional<T> findById(ID id).

如何使用它?
学习
Optional 用法. 这里是有关其规格的重要信息:

How to use that ?
Learning Optional usage. Here important information about its specification :

可能包含也可能不包含非null值的容器对象.如果一个 值存在,isPresent()将返回true,get()将返回 值.

A container object which may or may not contain a non-null value. If a value is present, isPresent() will return true and get() will return the value.

取决于存在或不存在的其他方法 提供包含的值,例如orElse()(返回默认值 如果不存在值)和ifPresent()(如果 值).

Additional methods that depend on the presence or absence of a contained value are provided, such as orElse() (return a default value if value not present) and ifPresent() (execute a block of code if the value is present).


关于如何将OptionalOptional<T> 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 three classical usage examples.

1)假设如果找到该实体,则要获取它,否则要获取默认值.

1) Suppose that if the entity is found you want to get it otherwise you want to get a default value.

您可以写:

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);

2)假设如果找到该实体,您想返回它,否则您想抛出一个异常.

2) Suppose that if the entity is found you want to return it, else you want to throw an exception.

您可以写:

return repository.findById(id)
        .orElseThrow(() -> new EntityNotFoundException(id));

3)假设您要根据是否找到实体来应用不同的处理(无需引发异常).

3) Suppose you want to apply a different processing according to if the entity is found or not (without necessary throwing an exception).

您可以写:

Optional<Foo> fooOptional = fooRepository.findById(id);
if (fooOptional.isPresent()){
    Foo foo = fooOptional.get();
   // processing with foo ...
}
else{
   // alternative processing....
}

这篇关于Spring Data JPA的findOne()更改为Optional怎么使用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆