当前位置: 代码迷 >> 综合 >> JpaObjectRetrievalFailureException: Unable to find xxx with id 1
  详细解决方案

JpaObjectRetrievalFailureException: Unable to find xxx with id 1

热度:44   发布时间:2024-02-28 11:33:44.0

在使用spring boot + jpa时遇到错误如下 

org.springframework.orm.jpa.JpaObjectRetrievalFailureException: Unable to find com.xxxx with id 1;
nested exception is javax.persistence.EntityNotFoundException: Unable to find com.xxxx with id 1

发现是使用 getOne() 方法报错

根据错误信息 with id 1的到是获取id为1的数据而数据库没有导致,不像mybatis那样数据库么有返回null,真坑

使用 findById(id).get() 查看源码发现也会报错

public T get() {if (value == null) {throw new NoSuchElementException("No value present");}return value;
}

findOne(example) 方法和findById 返回值一样所有也会报错,还要新建个example

所以

1.要么只能使用 existsById(id) 判断一下,这样的话如果存在就等于要访问两次数据库

2.要么就

try{}catch(JpaObjectRetrievalFailureException e){//使用findById就catch NoSuchElementException异常System.out.println("数据不存在")
}

如果有更好的解决办法望不吝指教

  相关解决方案