Search code examples
sqlhibernateormmappinghql

HQL Fetch Join without knowing object implementation


I'm having performance issues and I'm trying to add some fetch join to get some data in only one request.

My problem is : I got a mapped object AbstractObject. And I also got other mapped object like ObjectA, ObjectB etc... all are extending AbstractObject.

In my ObjectA I got a list of foos. In my ObjectB I got a list of otherFoos.

What I'm trying to do : I want to write a request like this :

entityManager.createQuery("SELECT ao FROM AbstractObject ao LEFT JOIN FETCH ao.foos LEFT JOIN FETCH ao.otherFoos WHERE ao.id = ?1", AbstractObject.class)

Problem: I got a nullPointerException because, I think, hibernate does not know foos or otherFoos for AbstractObject. In my point of view, I do not know if I will have a ObjectA or ObjectB.

Do someone know a solution for this issue ?

Hibernate version : 5.0.12.Final


Solution

  • In general, in order to execute an HQL query and return properties of multiple entities on the same result, you need a projection to a DTO.

    So you will create a DTO for example ObjectAB, which will not be mapped, it will probably extending both Object A and B and then you will create your query and set a result transformer to this DTO.

    Alternatively you could use a Tuple instead of a DTO, but this doesn't change the main idea. For more details of this methodology you may read this article.