Spring Data: JPA repository findAll() to return *Map instead of List?

与世无争的帅哥 提交于 2021-01-21 13:19:28

问题


I have a Spring Data JPA repository interface that looks something like this:

@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.


回答1:


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:

Map<Long, Transaction> transactionMap = transactionList.stream()
         .collect(Collectors.toMap(Transaction::getId, Function.identity()));



回答2:


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.

@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));
    }
}


来源:https://stackoverflow.com/questions/41876122/spring-data-jpa-repository-findall-to-return-map-instead-of-list

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!