Java Spring Data:JPA 存储库 findAll() 返回 *Map 而不是 List?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/41876122/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Spring Data: JPA repository findAll() to return *Map instead of List?
提问by Deniss M.
I have a Spring Data JPA repository interface that looks something like this:
我有一个看起来像这样的 Spring Data JPA 存储库接口:
@Repository
public interface DBReportRepository extends JpaRepository<TransactionModel, Long> {
List<TransactionModel> findAll();
List<TransactionModel> findByClientId(Long id);
}
Is there a workaround to make the same but for a Collection to be returned of type HashMap<K, V>
? I've looked through the Spring Data classes and couldn't find anything other than List<> return values.
是否有解决方法可以使相同但要返回类型的 Collection HashMap<K, V>
?我查看了 Spring Data 类,除了 List<> 返回值之外找不到任何其他内容。
采纳答案by Patrick
I dont think you will find an easier solution as to create a simple one liner to convert your result to a map. It is simple and fast with java 8 lambdas:
我不认为您会找到一个更简单的解决方案来创建一个简单的单衬纸来将您的结果转换为地图。使用 java 8 lambdas 既简单又快速:
Map<Long, Transaction> transactionMap = transactionList.stream()
.collect(Collectors.toMap(Transaction::getId, Function.identity()));
回答by Matt R
Just had to solve something similar and Patricks answer helped but it can be improved by indicating where to add it.
只需要解决类似的问题,帕特里克的回答有所帮助,但可以通过指示添加位置来改进。
To to make it appear like the JPA repo returns a map, an improvement would to wrap this up in a default method in the repository interface. Saves you having to perform a stream in all the consuming classes.
为了使它看起来像 JPA 存储库返回一个映射,改进将把它包装在存储库接口中的默认方法中。让您不必在所有消费类中执行流。
@Repository
public interface DBReportRepository extends JpaRepository<TransactionModel, Long> {
List<TransactionModel> findAll();
default Map<Long, TransactionModel> findAllMap() {
return findAll().stream().collect(Collectors.toMap(TransactionModel::getId, v -> v));
}
List<TransactionModel> findByClientId(Long id);
default Map<Long, TransactionModel> findByClientIdMap(Long id) {
return findByClientId(id).stream().collect(Collectors.toMap(TransactionModel::getId, v -> v));
}
}