Issue
(I made a SSCCE for this question.)
I have 2 simple entities : Employee
and Company
. Employee
has a @ManyToOne
relationship with Company
with default fetch strategy (eager).
I want to be able to load the Employee
without the Company
without changing the fetch strategy defined in the Employee
because I need to do that for only one use case.
JPA's entity graph seems to be intended for this purpose.
So I defined a @NamedEntityGraph
on the class Employee
:
@Entity
@NamedEntityGraph(name = "employeeOnly")
public class Employee {
@Id
private Integer id;
private String name;
private String surname;
@ManyToOne
private Company company;
//Getters & Setters
And a EmployeeRepository
like this :
public interface EmployeeRepository extends CrudRepository<Employee, Integer> {
@EntityGraph(value = "employeeOnly", type = EntityGraph.EntityGraphType.FETCH)
List<Employee> findByCompanyId(Integer companyId);
}
Despite the use of @EntityGraph
, I can see in the logs that the Company
is still loaded by hibernate :
2016-11-07 23:16:08.738 DEBUG 1029 --- [nio-8080-exec-2] org.hibernate.SQL : select employee0_.id as id1_1_, employee0_.company_id as company_4_1_, employee0_.name as name2_1_, employee0_.surname as surname3_1_ from employee employee0_ left outer join company company1_ on employee0_.company_id=company1_.id where company1_.id=?
2016-11-07 23:16:08.744 DEBUG 1029 --- [nio-8080-exec-2] org.hibernate.SQL : select company0_.id as id1_0_0_, company0_.name as name2_0_0_ from company company0_ where company0_.id=?
Why? How to avoid that?
Solution
Hibernate did not support handling non-lazy attributes as lazy, even with entity graphs. There was an issue for this: HHH-8776, but it's fixed now.
Previously, the only solution for the time being was to make the association lazy.
Answered By - Dragan Bozanovic
Answer Checked By - Marilyn (JavaFixing Volunteer)