Spring Boot中getById仅Debugger显异常、toString才触发捕获问题排查
问题原因与解决办法
这确实是**懒加载(延迟加载)**导致的,核心原因在于Spring Data JPA中getById()方法的特性:
getById(id)返回的是一个动态代理对象,而非真实的实体数据。这个代理不会立即执行数据库查询,只有当你调用实体的方法(比如toString()、getter方法等)时,才会触发实际的数据库访问操作。- 注释掉
author.toString()时,代码仅将代理对象加入集合,没有触发数据库查询,因此不会抛出EntityNotFoundException,catch块自然捕获不到异常。 - 取消注释
author.toString()后,方法调用触发了数据库查询,此时才会发现对应ID的实体不存在,抛出异常并被catch块捕获。 - 调试时计算
authorRepository.getById(authorId)会触发代理的方法调用,进而执行数据库查询,所以会显示抛出异常。
解决办法
如果希望在获取实体时立即触发查询并捕获异常,推荐改用findById(id).orElseThrow()方法,它会直接执行数据库查询,不存在则立刻抛出异常:
ArrayList<AuthorEntity> getAuthorArrayList(ArrayList<Integer> authorsIds) { ArrayList<AuthorEntity> result = new ArrayList<>(); for (Integer authorId : authorsIds) { try { AuthorEntity author = authorRepository.findById(authorId) .orElseThrow(() -> new EntityNotFoundException("Author not found with id: " + authorId)); result.add(author); } catch (EntityNotFoundException e) { System.out.println("EntityNotFoundException: " + e.getMessage()); } } return result; }
也可以保留getById(),但主动触发数据库访问:
// 需要引入Hibernate的initialize方法 import org.hibernate.Hibernate; // ... AuthorEntity author = authorRepository.getById(authorId); Hibernate.initialize(author); // 触发数据库查询,异常会在此处抛出 result.add(author); // ...
内容的提问来源于stack exchange,提问作者Kifsif
相关产品推荐
相关产品推荐

