Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make Hibernate Spring Repository to return HashMap

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
like image 939
Paul Avatar asked Feb 12 '15 01:02

Paul


1 Answers

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));
    }
}
like image 184
Ben Ketteridge Avatar answered Nov 15 '22 14:11

Ben Ketteridge