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

huangapple go评论61阅读模式
英文:

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&lt;StoredMessageModTrackEntity&gt; 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 -&gt; list.stream().map(mapper::toDtoMapper)
    .collect(Collectors.toList())).orElse(null);

huangapple
  • 本文由 发表于 2020年10月25日 22:05:22
  • 转载请务必保留本文链接:https://go.coder-hub.com/64524582.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定