Understanding how spring-data handles @EntityGraph

Arnaud Denoyelle :

(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 Companywithout 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 @NamedEntityGraphon 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?

Dragan Bozanovic :

Currently, Hibernate does not support handling non-lazy attributes as lazy, even with entity graphs. There is an open issue for this: HHH-8776.

So, the only solution for the time being is to make the association lazy.

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=453133&siteId=1