Can createNativeQuery of EnityManager return resultClass that is dojo class

I can have the following script:

1. I have an entity class – EntityClass (mapping with EntityTable)
2. I have a dojo class – DojoClass
3. Both of the classes have the same variables.


What will be returned when I call the following method:
A- entityManager.createNativeQuery("SELECT * FROM EntityTable",EntityClass.class);

B- entityManager.createNativeQuery("SELECT * FROM EntityTable",Dojo.class);

Are they correct?


This is quite an unusual use case and i am guessing only theoretical.

I have made configuration just as you have, most notably that both of the entities have exactly the same basic fields (these are the ones that will be taken under consideration while mapping the results to the classes).

I am using JPA 2.1 and Hibernate 5.x as the implementation under the hood.

To my bewilderment both queries run properly and assign the results as expected to corresponding fields in each of the classes.

I went a bit deeper into the implementation and basically what is happening behind the scenes is:

  • Creation of a list of type List<Object[]> as the first step, which is the standard behavior for the createNativeQuery(String) method without the class specified.
  • Setting the fields of a class using reflection. So it does not really matter from which table we are pulling the results.. the column names and types must match..

And few tips for the end:

  • Class specified as the second parameter has to always be a managed entity or embeddable
  • When i tried to query for only certain column(s) i was getting errors with the missing columns lacking in the query. So i guess you always have to select everything

Hope this clarifies things.

Leave a Reply

Your email address will not be published. Required fields are marked *