Search code examples
javahibernateleft-joinhql

Replicate Hibernate Eager loading using a fetch


I have a class called LocType which has 30 elements and a @OneToMany relation to LocProfile which has 40 elements. I have to do some calculations to figure which LocTypeProfile should be associated once a user picks a location, so it needs to be available at jsp side.

If I define the relationship for Eager initialization like below, when I retrieve elements from LocType it gives me 30 elements with the instances where one to many relationship stored in the list - which is the behavior I want.

@OneToMany(fetch = FetchType.EAGER, mappedBy = "LocType ", cascade = CascadeType.ALL) 
private List<LocTypeProfile > locTypeProfiles;

Now If I change the mapping to Lazy loading in the interest of good practice

@OneToMany(mappedBy = "creditTypes")

and try to query using a fetch

select lt from LocTypes lt left join fetch lt.locTypeProfiles

I get the 40 elements, where the data is flattened.

My question is is there a way to replicate the behavior of the Eager initialization in this scenario?


Solution

  • When doing a join fetch for a OneToMany relationship you need to use distinct in the select statement, otherwise an entity will be created for each row fetched.

    Try:

    select distinct lt from LocTypes lt left join fetch lt.locTypeProfiles
    

    Reference: One-To-Many relationship gets duplicate objects whithout using “distinct”.Why?