简体   繁体   中英

Hibernate left join returns objects

I'm doing a query which returns objects in stead of a custom class:

Query q = em.createQuery("FROM Author a LEFT JOIN a.documents d LEFT JOIN d.personDocuments pd WHERE pd.person = :person ORDER BY a.lastName");
q.setParameter("person", person);
return new HashSet<Author>(q.getResultList());

I would expect that q.getResultList() would return a list of Authors (and their linked documents), however it's a list of objects. What am I doing wrong?

The method getResultList() from Query is not typed.
Therefore it seems that it only returns Objects (which really are instances of Author in your case), which you manually have to cast to Author . (You can check what the Object really is by inspecting getClass() on an instance for example.)

You can use TypedQuery for typed queries, which will work as you need them.

TypedQuery<Author> q = em.createQuery("SELECT a FROM Author a LEFT JOIN a.documents d LEFT JOIN d.personDocuments pd WHERE pd.person = :person ORDER BY a.lastName", Author.class);
q.setParameter("person", person);
return new HashSet<Author>(q.getResultList());

This Tutorial from objectdb covers it quite well.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM