Nehal Damania
Nehal Damania

Reputation: 9008

Avoiding loading of Lazy Collections in QueryDSL, Hibernate and Spring Data JPA

I would like to avoid loading of few lazy collections when I run a query using QueryDSL.

@Entity
@Table(name = "employee")
public class Employee implements Serializable {

    @Id
    @Column(name = "id", nullable = false)
    @NotNull
    private String id;

    @OneToMany(cascade = CascadeType.ALL, orphanRemoval = true, fetch = FetchType.LAZY, mappedBy = "employee")
    @Fetch(FetchMode.JOIN)
    @JsonManagedReference
    private Set<Department> departments = new HashSet<Department>();

    @JsonManagedReference
    @OneToMany(cascade = CascadeType.ALL, orphanRemoval = true, fetch = FetchType.LAZY, mappedBy = "employee")
    @Fetch(FetchMode.JOIN)
    private Set<Location> locations= new HashSet<Locations>();
}

Now if I use the following Query

final QEmployee employee = QEvent.employee;

final List<Employee> employees = query.from(employee)
        .distinct()
        .leftJoin(event.departments).fetch()
        .list();

Now, what happens is Department table is joined properly, but it is then doing N+1 Selects for Location. I am using the result of the above query to build a DTO, so JSON is not getting triggered. In the logic, I am not accessing locations, still all the locations + all the tree under it is being fetched lazily. How, to prevent Locations from being fetched using QueryDSL.

Upvotes: 1

Views: 1733

Answers (1)

Nehal Damania
Nehal Damania

Reputation: 9008

The issue was @Fetch(FetchMode.JOIN) annotation at top of locations. I removed that and its working fine. Locations are now not getting fetched.

Upvotes: 1

Related Questions