英文:
Java Spring-boot: how to return a list and not a single result?
问题
我是Java和使用Spring Boot框架的新手。我已经实现了一个小方法,根据transactionId为我提供拥有该transactionId的所有对象的列表。我在ServiceImpl中只是在管理列表方面遇到问题,因为我无法获得一个列表而不是单个结果。
英文:
I'm new to Java and using the Spring-Boot framework. I have implemented a small method that given a transactionId gives me the list of all objects having that transactionId. I just have problems managing the list in the ServiceImpl. as I can't get a list back instead of a single result.
答案1
得分: 1
如果映射器适用于实体的单个实例,您可以简单地遍历实体集合,并逐个映射一个实体。或者您可以使用Java8流:
List<StoredMessageModTrackEntity> entityList = repo.findAllByTransactionId(transactionId);
return entityList.stream().map(mapper::toDtoMapper).collect(Collectors.toList());
与您的示例不同,上述代码片段将在entityList
为空时返回一个空列表。除非您明确需要返回null
(由于某些奇怪的API契约或类似情况),否则不应该将null
用于空集合。这只会导致冗长的代码,因为所有使用者都必须始终检查null
。如果您真的(我是说真的)需要null
,您可以保留您的if语句或使用Optional
:
Optional.ofNullable(entityList).filter(Objects::nonNull)
.map(list -> list.stream().map(mapper::toDtoMapper)
.collect(Collectors.toList())).orElse(null);
英文:
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. Or you use Java8 streams:
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. 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
. If you really (and I mean really) need null
, you can either keep your if-statement or use Optional
:
Optional.ofNullable(entityList).filter(Objects::nonNull)
.map(list -> list.stream().map(mapper::toDtoMapper)
.collect(Collectors.toList())).orElse(null);
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论