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.

6
  • 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); Commented Jul 22, 2016 at 19:08
  • 1
    You can't with a query alone in JPQL. Convert the results yourself into what you need Commented Jul 22, 2016 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 :). Commented Jul 22, 2016 at 19:16
  • 1
    let me post it as an answer to accept it :) Commented Jul 22, 2016 at 19:17
  • 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. Commented Jul 22, 2016 at 19:20

2 Answers 2

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();

Sign up to request clarification or add additional context in comments.

1 Comment

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 :)
1

Please try with

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.