在findAll()上处理空结果:列表是否有orElseThrow()? [英] Handling empty results on findAll(): Is there a orElseThrow() for lists?

查看:282
本文介绍了在findAll()上处理空结果:列表是否有orElseThrow()?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在创建一个Spring REST服务。我有一个 findById()呼叫:

I am creating a little Spring REST service. I have a findById() call:

@GetMapping("/items/{id}")
MyItem one(@PathVariable String id) {
    return repository.findById(id).orElseThrow(() -> new MyItemNotFoundException(id));
}

如果不存在具有给定 id的MyItem对象,我使用 Optional< T> .orElseThrow()方法抛出异常。

If there is no MyItem object with the given id, I am throwing an exception using the Optional<T>.orElseThrow() method. This is very useful and quite simple.

现在,我从<$ c $中添加了 findAll()调用c> PagingAndSorting< T,ID> 存储库:

Now I added a findAll() call from the PagingAndSorting<T, ID> repository:

@GetMapping("/items")
List<MyItem> all() {            
    return repository.findAll();
}

是否有一种简单的方法可以处理空列表输出可以用单个物品完成?还是我需要创建类似以下内容的东西:

Is there a simple way to handle empty list outputs in a similar way as it can be done with single items? Or do I need to create something like:

@GetMapping("/items")
List<MyItem> all() {    
    List<MyItem> items = repository.findAll();
    if  (items.isEmpty())
        throw new MyItemNotFoundException();        

    return items;
}

(实际用例处理一些请求参数以过滤整个列表)

(The real use case handles some request parameters to filter the whole list)

推荐答案

findById中 Optional 背后的原因避免返回 null

空集合是可以安全地进行迭代和处理,因此没有内置的特殊 .throwIfEmpty()机制。空集合本质上是一个Optional。它不是null,并且可能包含元素,也可能不包含元素。

Empty collections on the other hand are safe to iterate and handle, so there's no special .throwIfEmpty() mechanism built-in. An empty collection is essentially an Optional in itself. It's not null, and may or may not contain elements.

如果在您的业务逻辑中没有结果表示错误,则由您来处理。

If in your business logic no results means error, then it's up to you to handle it.

这篇关于在findAll()上处理空结果:列表是否有orElseThrow()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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