I am using Hibernate version 6.5.3.Final. Regarding fetching AEntity, I’m not entirely sure if I understand it correctly, but I’m retrieving data using Spring query methods as shown below:
When I query in this way, the generated queries result in an N+1 issue, as shown below:
select *
from a_table
where id = 1;
select *
from c_table
where a_id = 1;
BVO is a simple class containing only a few fields of AEntity (a_table), and I expected the List<CVo> to work with a @Fetch(FetchMode.JOIN) annotation, avoiding the N+1 issue and instead working as a left join fetch query like the following:
select *
from a_table left join c_table on a.id = c.a_id
where c.id = 1;
I’m not sure if I misunderstood something or if I’m missing some configuration.
This is not a forum for Spring Data questions. You will have to ask Spring people about what is happening under the hood.
I can tell you that if you use EntityManager#find, the fetch type will contribute into the SQL query. If you use a HQL/Criteria query e.g. EntityManager#createQuery, the fetch type won’t contribute to the SQL query, but will result in this sort of N+1 queries.
To solve this, you can use an entity graph which will contribute fetches to the SQL query in both cases or use an explicit HQL query with explicit join fetches.