As described in http://www.javacodegeeks.com/2012/07/ultimate-jpa-queries-and-tips-list-part_7092.html, you can get objects from a jpa query. So far, so good.
But since I will have to use this quite often, I want to use generics. So instead of
Query query = em.createQuery('select new com.model.PersonDogAmountReport(p, size(p.dogs)) from Person p');
I want
Query query = em.createQuery('select new com.model.Report<Person, Long>(p, size(p.dogs)) from Person p');
or
Query query = em.createQuery('select new com.model.Report<com.model.Person, java.lang.Long>(p, size(p.dogs)) from Person p');
. Trying this gives me the following exception:
org.hibernate.hql.ast.QuerySyntaxException: expecting OPEN, found '<' near line 1
Does this mean, that what I want is just not supported? Are there good alternatives?
Nearly the same thing is possible with NamedNativeQuery and resultClass, but that way I wouldn't get Person as an entity.
If I use object instead, the returned List cannot be cast, meaning I have to iterate -> meh desu.
Thanks in advance for any help.
Creating instances of Reports like this is not safe anyway, since Hibernate uses reflection to instantiate and populate the reports. So you could simply do:
Query query = em.createQuery('select new com.model.Report(p, size(p.dogs)) from Person p');
return (List<Report<Person, Long>>) query.list();
What you need to remember here is that with Java generics type-erasure will remove all generic types. This will reduce a List<Person>
to simply a List<Object>
with the appropriate casts. At runtime there is no such thing as a List<Person>
. So in a situation like this, just get a List
and do the casts yourself.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With