简体   繁体   English

Java Spring-boot:如何返回列表而不是单个结果?

[英]Java Spring-boot: how to return a list and not a single result?

I'm new to Java and using the Spring-Boot framework.我是 Java 的新手,正在使用 Spring-Boot 框架。 I have implemented a small method that given a transactionId gives me the list of all objects having that transactionId.我已经实现了一个小方法,给定一个 transactionId 给我一个具有该 transactionId 的所有对象的列表。 I just have problems managing the list in the ServiceImpl.我只是在管理 ServiceImpl 中的列表时遇到问题。 as I can't get a list back instead of a single result.因为我无法取回列表而不是单个结果。

If the mapper is working for a single instance of your entities, you can simply iterate over the entity collection and map one entity at a time.如果映射器正在为您的实体的单个实例工作,您可以简单地迭代实体集合和 map 一次一个实体。 Or you use Java8 streams:或者你使用 Java8 流:

List<StoredMessageModTrackEntity> entityList = repo.findAllByTransactionId(transactionId);
return entityList.stream().map(mapper::toDtoMapper).collect(Collectors.toList());

Unlike your example the above snippet will return an empty list, if entityList is empty.与您的示例不同,如果entityList为空,上面的代码片段将返回一个空列表。 Unless you explicitly need to return null (by some weird API contract or similar) you should not use null for empty collections. This will just result in bulky code as all consumers will always need to check for null .除非您明确需要返回null (通过一些奇怪的 API 合同或类似合同),否则您不应将null用于空 collections。这只会导致代码庞大,因为所有消费者将始终需要检查null If you really (and I mean really) need null , you can either keep your if-statement or use Optional :如果你真的(我的意思是真的)需要null ,你可以保留你的 if 语句或使用Optional

Optional.ofNullable(entityList).filter(Objects::nonNull)
    .map(list -> list.stream().map(mapper::toDtoMapper)
    .collect(Collectors.toList())).orElse(null);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM