1

I have an Entity A which contains a @OneToOne relation to the Entity B. Entity B have, in turn, a @OneToOne relation to Entity C:

A
| 
|--B  @OneToOne
   |
   |--C   @OneToOne

I need to select all data of Entity A with some fields of Entity B. Fields of Entity C have to be ignored.

Knowing that in Hibernate default fetch type for *ToOne relations is EADGER, when getResultList of criteria Api is called on Entity A, N+1 query are executed (3 select).

I'm using Spring Data JPA with Spring Boot over an Oracle DB.

To avoid this problem and to execute only single query, I configured a right join fetch from Entity A to Entity B.

With this configuration I'm expecting tosolve the issue, but i noticed that hibernate execute two select and not one. It retrieve Entity A and Entity B into the same query, as configured in the fetch, but execute an extra query to load C.

To solve, I need to configure the right join fetch also for Entity C.

Is this the right approach? I'm in toruble because this is a simple case, but what happens in complex case, with many relations and nested elements? Is there a way to ignore nested relations?

I also tried to use right join fetch on Entity A in cojiunction with @LazyToOne (instrumenting at compile time). But it execute always two query:

The first one, on query.getResultList(), is the right query, and rightly retrieve all required data.

The second one, is triggered by Hibernate when i try to access B entity with getB(). This query have a strange behavior: it retrieve the ID of Entity B from Entity A.

Something like: Select b.id from a where a. Id=?

I don't know why it execute this extra query!

How to solve in an elegant way?

Thank you

0 Answers0