Search code examples
sqlhibernatejpa

JPA get result list order by selected columns


I have a native query

searchSql = "Select  firstname,lastname from students order by id desc"

and then i do

    Query query = entityManager.createNativeQuery(searchSql);
    List<Map<String, Object>> results = query.getResultList();

Now if i print the results with KEYS

  List<String>headers = new ArrayList<>();
  for(String header : results.get(0).keySet()){
          headers.add(header);
  }

i get random order of the column names.
How can i get the exact order as in the select statement ?
LinkedHashMap should be the answer but i get class cast exceptions... Any generic ideas?


Solution

  • I checked if LinkedHashMap causes the randomness of columns:

    @Test
    public void linkedHashMap() {
        Map<String, Integer> map = new LinkedHashMap<>();
        IntStream.range(0, 10).forEach(integer -> {
            map.put(
                String.valueOf(integer), 
                integer
            );
        });
    
        for (String val : map.keySet()){
            System.out.println(val);
        }
    }
    

    but instead it prints:

    0
    1
    2
    3
    4
    5
    6
    7
    8
    9
    

    The randomness seems to be a limitation of Hibernate, as stated here