Ali Ali - 3 months ago 36
Java Question

JPA return HashMap<Integer,ArrayList<Integer>> using Native or Named Query

i have a table with the folowing structure :

ID id_client id_order

1 1 10
2 1 15
3 1 13
4 2 20
5 2 40
6 2 9


my issue is : how to create a query(named or native) that return the result as

HashMap<Integer,ArrayList<Integer>>


my map contains a unique id_client with an arrayList of all id_order:

1=>10,15,13

2=>20,40,9


note ; i'm using EclipseLink as a JPA implementation

thanks in advance.

Ali Ali
Answer

this is how to deal with this issue , you should use Stream API.

 List<Entity> listEntity = yourservicenameTogetDataFromDataBase();

//grouping By id_client 
Map<Integer, List<Integer>> groupingMap = listEntity
      .stream()
   .collect(Collectors.groupingBy(o->o.getIdClient()));

//result

for (Entry<Integer, List<Integer>> entry : groupingMap.entrySet()) {
        System.err.println("Key = " + entry.getKey() +" , Values :");
          for (Integer  i : entry.getValue()) {
      System.err.println(i);

      }
  }

Key = 1 , Values :
  10
  15
  13

Key = 2 , Values :

  20
  40
  9
.....