JpaObjectRetrievalFailureException: Unable to find xxx with id 1

r囧r小猫 2022-12-15 02:20 207阅读 0赞

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

  1. org.springframework.orm.jpa.JpaObjectRetrievalFailureException: Unable to find com.xxxx with id 1;
  2. 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() 查看源码发现也会报错

  1. public T get() {
  2. if (value == null) {
  3. throw new NoSuchElementException("No value present");
  4. }
  5. return value;
  6. }

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

所以

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

2.要么就

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

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

发表评论

表情:
评论列表 (有 0 条评论,207人围观)

还没有评论,来说两句吧...

相关阅读