Generally we write the query as
@Query("SELECT a FROM Foo a WHERE a.someId = :id")
Map<Long, Foo> findAllBySomeId(Long id)
Is there a way to get it HashMap instead of List.
I want the key of the Hashmap's key=someId and Value as Foo.
I tried like this
@Query("SELECT new map (a.someId, a) FROM Foo a WHERE a.someId = :id")
Map<Long, Foo> findAllBySomeIdAsMap(Long id);
but it returned two items but a.someId as Value and key as 0;
0=someId
1=Foo
I've tackled a similar mapping problem (where I wanted to load every value in a static data table as I know I'll need them all in a process). So this is my solution to this problem (admittedly without the 'where a.someId = id'). It uses findAll(), I'm sure it could use any other 'find' method with your id limitation.
public interface FooRepository extends JpaRepository<Foo, String> {
// convenience method to provide a 'code -> object' mapping of all Foos
default Map<String, Foo> mapAll() {
return findAll().stream().collect(Collectors.toMap(o -> o.getCode(), o -> o));
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With