Hibernate initializing a group/collection of entities

Clash Royale CLAN TAG#URR8PPP
Hibernate initializing a group/collection of entities
I have a query with fetches an entity in pages. Each page contains 100 entities. For those 100 entities I need to fetch some nested entities which are fetched lazy.
What happens is that I have 1 SELECT executed for main entities and then 100 SELECTs for nested ones.
I am looking for a way to initialize those 100 nested ones in bulk, so that in total I have 1 SELECT for main entity and 1 for nested ones.
My structure is as follows, and I would prefer if it is not changed (we had a lot of problems with EAGER fetches)
public class MyMainEntity {
private NestedEntity nested;
@Override
@OneToOne(fetch = FetchType.LAZY, cascade = CascadeType.ALL, orphanRemoval = true)
@JoinColumn(foreignKey = @ForeignKey(name = "exFK_Nest_Enth"))
public NestedEntity getNested()
...
Is there a way to do it with Hibernate.initialize()
Hibernate.initialize()
eager
Its just SimpleJpaRepository findAll(Specification<T> spec, Pageable pageable) method. All kind of problems with different entities. So I would like to avoid that. But it seams that its not possible to be done with hibernate. I have decided to write special queries and select only fields which I need. That way nothing will be LAZY fetched.
– mirzak
Sep 7 at 8:18
2 Answers
2
You can use Hibernate Criteria query to fetch the MyMainEntity and use criteria.createAlias("nested", "ns", Criteria.Subselect). It will fire two query; one for fetching MyMainEntity and other for Nested with MyMainEntity query acting as subquery. And if you use Criteria.Join then it will fire only one query and fetching both MyMainActivity and Nested
By default, hibernate recent versions it follows JPA 2.0 spec:
Relationships with:
ToMany: Lazy
ToOne: Eager
In that case when you want to try to retrieve child relations use JOIN FETCH , for example:
JOIN FETCH
Select m from MyMainEntity m JOIN FETCH m.nested;
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.
Can you share the repository code? Also what kind of problems did you have with
eagerfetching?– Aris_Kortex
Sep 7 at 8:14