The @ElementCollection values inside an @Embeddable VO are not being fetched with a left outer join (eager fetch) as expected

There is an AEntity that contains a BVO. The BVO represents a few columns of the AEntity.

Additionally, there is a CVO, which is a separate table and exists inside the BVO. The CVO is managed as a collection type with a 1:N relationship.

When AEntity is queried, I want it to be fetched with a single query using a left join. However, it is being fetched lazily instead.

I’d like to understand what the problem is.

Here’s the code:

@Entity
@Table(name = "a_table")
public class AEntity {

    @Id
    private Long id;

    @Embedded
    private BVo bVo;
}
@Embeddable
public class BVo {

    @ElementCollection(fetch = FetchType.EAGER)
    @Fetch(FetchMode.JOIN)
    @CollectionTable(name = "c_table", joinColumns = @JoinColumn(name = "a_id"))
    private List<CVo> cVoList = new ArrayList<>();


}
@Embeddable
public class CVo {

}

What version of Hibernate ORM are you using? How are you fetching AEntity? What SQL queries are generated?

Hello @beikov,

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:

AEntityRepository.findAll();
AEntityRepository.findAllById(Long id);

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.

Thank you for your attention.

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.