Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JPA 2.0 native query results as map

Tags:

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 
like image 259
kovica Avatar asked Sep 29 '11 09:09

kovica


People also ask

Can JPA return results as a map?

There is no standard way to get JPA to return a map.

How do you map native query results to entities?

The easiest way to map a query result to an entity is to provide the entity class as a parameter to the createNativeQuery(String sqlString, Class resultClass) method of the EntityManager and use the default mapping. The following snippet shows how this is done with a very simple query.

How do you return DTOs from native queries with Spring Data JPA?

Spring Data JPA doesn't provide an automatic mapping of class-based DTOs for native queries. The easiest way to use this projection is to define your query as a @NamedNativeQuery and assign an @SqlResultSetMapping that defines a constructor result mapping.

What is the difference between native query and JPA query?

In JPA, you can create a query using entityManager. createQuery() . You can look into API for more detail. Native query refers to actual sql queries (referring to actual database objects).


1 Answers

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

Query query = entityManager.createNativeQuery(sql); query.setHint(QueryHints.RESULT_TYPE, ResultType.Map); 

For Hibernate, with javax.persistence.Query dbQuery:

org.hibernate.Query hibernateQuery =((org.hibernate.jpa.HibernateQuery)dbQuery) .getHibernateQuery(); hibernateQuery.setResultTransformer(AliasToEntityMapResultTransformer.INSTANCE); 
like image 62
wrschneider Avatar answered Sep 19 '22 08:09

wrschneider