Search code examples
javahibernatejpanativequeryhibernate-native-query

Java nativeQuery: ResultSet with AliasToEntityMapResultTransformer has unordered columns in map


I'm trying to get the resultset as a map and I'm successfully able to get it into a map. But the map keys are not as per the order of select query

Please check the code:

String queryString = "SELECT T1.COLUMN_11, T1.COLUMN_12, T2.COLUMN_21, T2.COLUMN_22 FROM MYSCHEMA.TABLE1 T1 INNER JOIN MYSCHEMA.TABLE2 T2 ON T1.SOME_COLUMN = T2.SOME_OTHER_COLUMN";

Query query = entityManager.createNativeQuery(queryString)
                       .unwrap(org.hibernate.query.Query.class)
                       .setResultTransformer(AliasToEntityMapResultTransformer.INSTANCE);
        
List<Map<String, Object>> resultSet = queryEx.getResultList();

Now as per expectation the List<Map<String, Object>> resultSet should look something like below

[
  {
    "COLUMN_11": "VALUE11",
    "COLUMN_12": "VALUE12",
    "COLUMN_21": "VALUE21",
    "COLUMN_22": "VALUE22"
  },
  ...............
]

But the colums are jumbled something like below

[
  {
    "COLUMN_21": "VALUE21",
    "COLUMN_12": "VALUE12",
    "COLUMN_11": "VALUE11",
    "COLUMN_22": "VALUE22"
  },
  ...............
]

Is there anyway I can retain the order as in select statement ?

PS: Can't create a model to hold the resultSet values as query is dynamic. So "HAD TO" use map only.


Solution

  • Try to remove .setResultTransformer(AliasToEntityMapResultTransformer.INSTANCE). I'm not an Hibernate expert but most JPA implementation return a list of Object arrays by default that preserve the order of the columns.

    An alternative would be to implement your own transformer where you use a LinkedHashMap instead of a HashMap. AliasToEntityMapResultTransformer uses HashMap.