1

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.

Kim Aragon Escobar
  • 166
  • 1
  • 2
  • 15
  • 1
    does sth like this work for you? `Query q1 = entityManager().query(nativeQuery); org.hibernate.Query hibernateQuery =((org.hibernate.jpa.HibernateQuery)q1) .getHibernateQuery(); hibernateQuery.setResultTransformer(AliasToEntityMapResultTransformer.INSTANCE);` – Apostolos Jul 22 '16 at 19:08
  • 1
    You can't with a query alone in JPQL. Convert the results yourself into what you need –  Jul 22 '16 at 19:09
  • @Apostolos Thank you very much, this solved my problem :D. This will tie my application to Hibernate but it's not a problem right now :). – Kim Aragon Escobar Jul 22 '16 at 19:16
  • 1
    let me post it as an answer to accept it :) – Apostolos Jul 22 '16 at 19:17
  • @BillyFrost Yep I was doing the conversion by myself until I saw the Apostolos 's answer. I don't mind to tie my application to a JPA implementation (hibernate in this case). – Kim Aragon Escobar Jul 22 '16 at 19:18
  • 1
    sometimes i also try not to do jpa-implementation-library-specific stuff but what are the chances of changing library? so instead of struggling to find a JPA-generic solution, in some parts of code i prefer using hibernate-specific parts too. – Apostolos Jul 22 '16 at 19:20

2 Answers2

2

You can to use the ResultTransformer to transform your results in a map form. Following the oficial documentation

Like this:

List<Map<String,Object>> mapaEntity = session
    .createQuery( "select e  from Entity" )
    .setResultTransformer(new AliasToEntityMapResultTransformer())
    .list();
  • This seems to be a cleaner solution, but in my current application I don't have access to the `org.hibernate.Session` :(, but thanks for you answer :) – Kim Aragon Escobar Jul 25 '16 at 13:54
1

Please try with

Query q1 = entityManager().query(nativeQuery); 
org.hibernate.Query hibernateQuery =((org.hibernate.jpa.HibernateQuery)q1) .getHibernateQuery(); 
hibernateQuery.setResultTransformer(AliasToEntityMapResultTransformer.INSTANCE);‌​
Apostolos
  • 10,033
  • 5
  • 24
  • 39