Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get generic object from hibernate query

Tags:

java

generics

jpa

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.

like image 941
Thomas Avatar asked Jan 16 '23 00:01

Thomas


2 Answers

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();
like image 106
JB Nizet Avatar answered Jan 25 '23 12:01

JB Nizet


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.

like image 39
John B Avatar answered Jan 25 '23 13:01

John B