Kim Aragon Escobar Kim Aragon Escobar - 4 months ago 18
Java Question

How to return List<Map<String, Object>> using JPA

I want to return a List of maps from my

createNativeQuery().getResultList()
, where each map is a pair key - value representing column name - value. I already tried to use direct in the method like this:

public List<Map<String, Object>> execQuery(String nativeQuery) {
return entityManager().query(nativeQuery).getResultList();
}


but it always return List. Someone knows if what I want is even possible?

The JPA implementation that I'm using is Hibernate. I'm currently using Java 8 (don't know if this information is relevant for my case).

Any help is welcome.
Thanks in advance.

Answer

Please try with

Query q1 = entityManager().query(nativeQuery); 
org.hibernate.Query hibernateQuery =((org.hibernate.jpa.HibernateQuery)q1) .getHibernateQuery(); 
hibernateQuery.setResultTransformer(AliasToEntityMapResultTransformer.INSTANCE);‌​