首页 > 解决方案 > 防止 Spring JPA 将异常包装到 JpaObjectRetrievalFailureException

问题描述

我正在尝试使用自定义存储库,该存储库允许在找不到实体时抛出明确措辞的异常。它看起来像这样:

public interface ItemRepository extends JpaRepository<Item, String>, ItemRepositoryCustom {

    Optional<Item> findByItemNumber(String itemNumber);
}
public interface ItemRepositoryCustom {

    Item findByItemNumberOrThrow(String itemNumber);
}
public class ItemRepositoryCustomImpl implements ItemRepositoryCustom {

    @Autowired
    ItemRepository itemRepository;

    @Override
    public Item findByItemNumberOrThrow(String itemNumber) {
        return itemRepository.findByItemNumber(itemNumber).orElseThrow(() ->
            new EntityNotFoundException(String.format("The Item with the number %s was not found", itemNumber)));
    }
}

我从How to throw exceptions on search methods in spring data jpa 中得到了这个想法。

这种结构原则上是有效的。但是,Spring JPA 似乎包装了这些异常,并且总是抛出 JpaObjectRetrievalFailureException,原因是我的 EntityNotFoundException。

但我不想那样!我们有专门处理 EntityNotFoundExceptions 的 ControllerAdvice,所以我想保持这种状态。

关于如何阻止 Spring JPA 这样做的任何建议?提前致谢!

标签: spring-bootexceptionspring-data-jpa

解决方案


推荐阅读