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

后端 未结 2 1925
臣服心动
臣服心动 2021-02-20 10:12

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

@Repository
public interface DBReportRepository extends JpaRepository

        
相关标签:
2条回答
  • 2021-02-20 10:49

    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()));
    
    0 讨论(0)
  • 2021-02-20 10:50

    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));
        }
    }
    
    0 讨论(0)
提交回复
热议问题