A Spring Data Repository typically returns entities or List of Object arrays List<Object[]> – for custom queries, not collections like HashMap<K, V> directly. You can structure a custom query or a method that returns a Map
in your Service or in additional method, but it’s not automatic — you have to be explicit about it.
Example: Custom Repository Method Returning a Map
Let’s say you have an entity:
@Entity
public class Product {
@Id
private Long id;
private String name;
private Double price;
// getters and setters
}
If you want to return a Map<String, Double>
(e.g., product name to price), you can write a custom query like this:
Option 1: Use @Query
and Stream it
public interface ProductRepository extends JpaRepository<Product, Long> {
@Query("SELECT p.name, p.price FROM Product p")
List<Object[]> findNameAndPricePairs();
default Map<String, Double> getNamePriceMap() {
return findNameAndPricePairs()
.stream()
.collect(Collectors.toMap(
row -> (String) row[0],
row -> (Double) row[1]
));
}
}
Option 2: Use a custom DTO and convert manually
public interface ProductRepository extends JpaRepository<Product, Long> {
@Query("SELECT new com.example.NamePriceDTO(p.name, p.price) FROM Product p")
List<NamePriceDTO> findAllNamePrice();
}
Then convert that list into a map in service layer:
Map<String, Double> namePriceMap = repository.findAllNamePrice()
.stream()
.collect(Collectors.toMap(NamePriceDTO::getName, NamePriceDTO::getPrice));
TL;DR
No, Spring Data Repository doesn’t directly return HashMap<K, V>
, but you can:
- Use
@Query
to extract pairs, - Convert to
Map<K, V>
manually in the repo default method or in the service layer.