英文:
Java nativeQuery: ResultSet with AliasToEntityMapResultTransformer has unordered columns in map
问题
我正在尝试将结果集作为映射获取,并且成功地将其放入了映射中。但是映射键的顺序与选择查询的顺序不同。
请检查以下代码:
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();
现在,按照期望,List<Map<String, Object>> resultSet
应该看起来像下面这样:
[
{
"COLUMN_11": "VALUE11",
"COLUMN_12": "VALUE12",
"COLUMN_21": "VALUE21",
"COLUMN_22": "VALUE22"
},
...............
]
但是列的顺序混乱,类似于下面这样:
[
{
"COLUMN_21": "VALUE21",
"COLUMN_12": "VALUE12",
"COLUMN_11": "VALUE11",
"COLUMN_22": "VALUE22"
},
...............
]
是否有任何方法可以保留与选择语句中相同的顺序?
注:由于查询是动态的,无法创建一个模型来保存结果集值,所以必须只能使用映射。
英文:
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.
答案1
得分: 2
尝试移除<code>.setResultTransformer(AliasToEntityMapResultTransformer.INSTANCE)</code>。我不是Hibernate专家,但大多数JPA实现默认返回保留列顺序的对象数组列表。
另一种方法是实现自己的转换器,在其中使用LinkedHashMap而不是HashMap。AliasToEntityMapResultTransformer使用HashMap。
英文:
Try to remove <code>.setResultTransformer(AliasToEntityMapResultTransformer.INSTANCE)</code>. 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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论