Search code examples
javaspring-bootspring-dataspring-data-jpa

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


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.


Solution

  • I don't 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()));