createNativeQuery mapping to POJO (non-entity)
Put your @SqlResultSetMapping annotation in a class which is an actual entity, not in the DTO Class. Your entity manager can not discover your mapping when you annotate a SqlResultSetMapping in a non-entity.
@SqlResultSetMapping(name = "AggregateStatsResult", classes = {
@ConstructorResult(targetClass = AggregateStatsDto.class,
columns = {
@ColumnResult(name = "total"),
@ColumnResult(name = "totalSum")
})
})
@Entity
public class SomeOtherClassWhichIsAnEntity {
I resolved my problem in following way: This is a query:
final Query query = Sale.entityManager().createNativeQuery(...);
Then I accessed to internal Hibernate session inside entity manager and applied scalars/resultTransformer. Thats all!
// access to internal Hibernate of EntityManager
query.unwrap(SQLQuery.class)
.addScalar("total", LongType.INSTANCE)
.addScalar("amountOfSales", LongType.INSTANCE)
.addScalar("amountOfProducts", LongType.INSTANCE)
.setResultTransformer(Transformers.aliasToBean(SaleStatsInfo.class));
...
query.getSingleResult();
This is not the suggested way . The more efficient way is mentioned above with @SqlResultSetMapping but in case you want something more hardcore you can access the Entity Manager's result by the object it returns .
For instance :
Query q = getEntityManager().createNativeQuery(queryString);
Trggering that with q.getSingleResult();
brings back to u an Object of type java.util.HashMap
which you can use to access your results row by row .
For instance:
Query q = getEntityManager().createNativeQuery(queryString);
java.util.HashMap res = (java.util.HashMap) q.getSingleResult();
for (Object key : res.keySet()) {
System.out.println(key.toString());
System.out.println( res.get(key).toString());
}