(Spring Boot)可以是Optional<>类就像List<>班级? [英] (Spring boot) can Optional<> Class be like List<> Class?

查看:102
本文介绍了(Spring Boot)可以是Optional<>类就像List<>班级?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图将RoomEntity类作为其通用参数放入列表中,但是列表类变为红色(错误),它唯一建议我将列表类更改为可选类.

Im trying to put the RoomEntity Class in the List as its generic parameter but the List Class turns red(Error) and the only thing that it suggests is for me to change the List Class to Optional Class.

public interface RoomRepository extends CrudRepository<RoomEntity, Long> {
    List<RoomEntity> findById(Long id);
}

RoomEntity类

RoomEntity Class

@Entity
@Table(name = "Room")
public class RoomEntity {

}

它们相同吗?

List<RoomEntity> findById(Long id); 
Optional<RoomEntity> findById(Long id);

推荐答案

可选和列表是两个非常不同的概念.

Optional and List are two very different concepts.

CrudRepository findAllById方法返回一个Iterable. findById方法返回一个Optional.

The CrudRepository findAllById method returns an Iterable. The findById method returns an Optional.

一个iterable可以用来一个集合地访问元素,因此可以与List类一起使用.

An iterable can be used to access one by one the elements of a collection and so can be used in conjunction with the List class.

一个Optional是一个容器对象,它可以包含也可以不包含非空值(零个或一个元素).这将只有一个元素,如果有的话,列表中的元素就不会很多.

An Optional is a container object which may or may not contain a non-null value (zero or one elements). This will have a single element in it, not many elements like in a List, if there is one.

CrudRepository :: findAllById可以发送一个以上的ID,因此可以返回多个元素,这样做的方式是返回一个可迭代的对象,您可以使用它逐个选择每个返回的结果.只能向findById方法发送一个ID,因此如果存在该元素(则包装在Optional中),则返回该元素;如果不存在,则返回Optional.none.

The CrudRepository::findAllById can have more than one ID sent to it and so can return more than one element, the way it does this is to return an iterable you can use to select each of the returned results one by one. The findById method can only be sent a single ID and so returns that element if it is present (wrapped in an Optional), or an Optional.none if it is not.

如果由于打算发送多个ID而正在寻找要返回的列表,请使用findAllById方法.如果只需要按ID指定特定元素,则可以使用findById方法,但是必须先将返回的Optional对象解开,然后才能使用Optional.get,Optional.isPresent或使用在流管道中对其进行地图或平面图调用.

If you are looking for a list to be returned because you intend to send in multiple IDs then use the findAllById method. If you want a specific element by ID only, then use the findById method but then you will have to unwrap the Optional object it is returned in before you can use it outside of a stream pipeline using Optional.get, Optional.isPresent, or using a map or flatmap call over it in a streams pipeline.

这篇关于(Spring Boot)可以是Optional&lt;&gt;类就像List&lt;&gt;班级?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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