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
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:
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.
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.