JPA 2.0 本机查询结果作为地图
我运行 JPA 2.0 本机查询,如下所示:
Query query = em.createNativeQuery("SELECT NAME, SURNAME, AGE FROM PERSON");
List list = query.getResultList();
现在 list
包含查询返回的所有行。我可以迭代它们,但每个条目都是一个 Object[]
其中:
- 在索引 0 处我找到了 NAME
- 在索引 1 处找到 SURNAME
- 在索引 3 处我找到了 AGE
有没有人找到一种方法来做这样的事情:
Map<String, Object> row = list.get(index);
String name = row.get("NAME");
String surname = row.get("SURNAME");
Integer age = row.get("AGE");
我需要这个,因为我执行的本机查询是动态的,我不知道SELECT 子句中字段的顺序,所以我不知道查询的 id 会是什么样子:
SELECT SURNAME, NAME, AGE FROM PERSON
或
SELECT AGE, NAME, SURNAME FROM PERSON
甚至
SELECT AGE, SURNAME, NAME FROM PERSON
I run a JPA 2.0 native query like this:
Query query = em.createNativeQuery("SELECT NAME, SURNAME, AGE FROM PERSON");
List list = query.getResultList();
now list
has all the rows returned by the query. I can iterate over them, but every entry is an Object[]
where:
- at index 0 I find NAME
- at index 1 I find SURNAME
- at index 3 I find AGE
Did anyone find a way to do something like this:
Map<String, Object> row = list.get(index);
String name = row.get("NAME");
String surname = row.get("SURNAME");
Integer age = row.get("AGE");
I would need this since the native query that I execute is a dynamic one and I don't know the order of the field in SELECT clause, so I don't know id the query will look like:
SELECT SURNAME, NAME, AGE FROM PERSON
or
SELECT AGE, NAME, SURNAME FROM PERSON
or even
SELECT AGE, SURNAME, NAME FROM PERSON
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您使用哪种 JPA - Hibernate、EclipseLink 还是其他?
在 JPA 中没有标准方法可以执行此操作,但您的特定实现可能允许这样做 - 例如,Eclipselink 有一个查询结果类型提示。
http://dev.eclipse.org/mhonarc/lists/eclipselink-users /msg03013.html
对于 Hibernate,使用 javax.persistence.Query dbQuery:
Which JPA are you using - Hibernate, EclipseLink or something else?
There is no standard way to do this in JPA but your specific implementation may allow it - for example, Eclipselink has a query result type hint.
http://dev.eclipse.org/mhonarc/lists/eclipselink-users/msg03013.html
For Hibernate, with javax.persistence.Query dbQuery:
正如其他人已经提到的,较旧的 JPA 不支持它,但是在我的情况下,在使用 Jackson 时,我有使用 Postgres 9.4 的解决方案,
要在Bean层使用它,请使用以下方法,否则直接返回。
更多 json 函数, https://www.postgresql.org/docs/ 9.4/static/functions-json.html。我相信您可以在其他数据库中找到相同的内容。
As other already mentioned, older
JPA
does not support it, however I have workaround solution withPostgres 9.4
in my situation, while working withJackson
,To use it in Bean layer use below method, otherwise directly return.
Few more json functions, https://www.postgresql.org/docs/9.4/static/functions-json.html. I am sure you can find same for other databases.
看看这个,我在做项目时发现我无法使用所有 JPA 功能,所以我尝试了传统的 jdbc 方法,即使我不推荐这个方法,但它对我有用。
Take a look on this I got it when working on project that I could not use all JPA features so I tried the traditional jdbc method even if I would not recommend this but it's working for me.