1、包装类
在springBoot 2.0 中,findById(id) 的返回值是Optional,Optional 是一个包装类,是对user 进行包装,在返回User的时候需要使用get() 方法。
2、findByid(id),findOne(id)和getOne(id)的区别
getOne:当我查询一个不存在的id数据时,直接抛出异常,因为它返回的是一个引用,简单点说就是一个代理对象。
所以说,如果想无论如何都有一个返回,那么就用findOne,否则使用getOne。 只是在2.0版本中没有findOne(id) 但是有 findById(id) 只是要稍微处理一下,需要用get()方法。
3、get()方法源码
/**
* If a value is present in this {@code Optional}, returns the value,
* otherwise throws {@code NoSuchElementException}.
*
* @return the non-null value held by this {@code Optional}
* @throws NoSuchElementException if there is no value present
*
* @see Optional#isPresent()
*/
public T get() {
if (value == null) {
throw new NoSuchElementException("No value present");
}
return value;
}