为什么 Spring Data 存储库上的 getOne(...) 不会抛出 EntityNotFoundException? [英] Why does getOne(…) on a Spring Data repository not throw an EntityNotFoundException?

查看:13
本文介绍了为什么 Spring Data 存储库上的 getOne(...) 不会抛出 EntityNotFoundException?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在处理一个奇怪的问题,我正在做集成测试,调用我的控制器从数据库中获取一个不存在的对象.

I'm working on a weird issue, I was doing integration testing, calling my controller to get an object from database that doesn't exist.

public Optional<T> get(Long id) {

  try {
    return Optional.ofNullable(repository.getOne(id));
  } catch(EntityNotFoundException e) {
    return Optional.empty();
  }
}

getOne(...) 找不到任何东西时,我期待一个 EntityNotFoundException 但实际上什么都没有.如果我检查我的结果,我可以看到我有一个空实体,它带有一个指向它的处理程序链接抛出 EntityNotFoundException",但我们没有进入捕获,我返回了这个奇怪实体的一个可选.

When getOne(…) is not able to find anything, I was expecting an EntityNotFoundException but actually nothing. If I inspect my result I can see that I have an empty entity with a handler link to it "threw EntityNotFoundException" but we don't go in the catch and I return an optional of this weird entity.

我无法理解这种行为.

推荐答案

这是由于 JPA 指定 EntityManager.getReference(...) 工作的方式.它应该返回一个代理,该代理将在第一次访问属性时解析要返回的对象,或者最终抛出包含的异常.

This is due to the way JPA specifies EntityManager.getReference(…) to work. It's supposed to return a proxy that will either resolve the object to be returned on the first access of a property or throw the contained exception eventually.

解决此问题的最简单方法是简单地使用 findOne(…) 代替,例如 Optional.ofNullable(repository.findOne(…)).findOne(…) 将返回 null 如果没有找到结果.

The easiest way to work around this is to simply use findOne(…) instead, like this Optional.ofNullable(repository.findOne(…)). findOne(…) will return nullin case no result is found.

解决此问题的更高级方法是让存储库直接返回 Optional 实例.这可以通过使用 Optional 作为 find...-methods 的返回类型创建自定义基础存储库接口来实现.

A more advanced way of resolving this is to make the repository return Optional instances directly. This can be achieved by creating a custom base repository interface using Optional<T> as return type for the find…-methods.

interface BaseRepository<T, ID extends Serializable> extends Repository<T, ID> {

  Optional<T> findOne(ID id);

  // declare additional methods if needed
}

interface YourRepository extends BaseRepository<DomainClass, Long> { … }

Spring 数据示例存储库.

这篇关于为什么 Spring Data 存储库上的 getOne(...) 不会抛出 EntityNotFoundException?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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