I would suggest a slightly different approach that can satisfy your needs.
JPA 2.1 has a feature called "displaying a result set."
Basically you should define a POJO class that will contain the result values ββ(all values ββshould be passed using the constructor):
public class ResultClass{ private String fieldOne; private String fieldTwo; public ResultClass(String fieldOne, String fieldTwo){ this.fieldOne = fieldOne; this.fieldTwo = fieldTwo; } }
Then you need to declare a match on one of your objects (no matter on what basis this should be declared by @Entity):
@SqlResultSetMapping(name="ResultMapping", classes = { @ConstructorResult(targetClass = ResultClass.class, columns = {@ColumnResult(name="columnOne"), @ColumnResult(name="columnTwo")}) })
columnOne and columnTwo are aliases declared in the select clause of a custom query.
And finally, use in creating the query:
List<ResultClass> results = em.createNativeQuery(query, "ResultMapping").getResultList();
In my opinion, this is more elegant and "above the level", since you do not work with generic Map key / value pairs, but with a specific POJO class.
source share