了解弹簧数据如何处理@EntityGraph
2022-09-03 06:37:02
(我为这个问题做了一个SSCCE。
我有2个简单的实体:和。 与默认抓取策略(eager )有关系。Employee
Company
Employee
@ManyToOne
Company
我希望能够在不更改中定义的获取策略的情况下加载,因为我只需要为一个用例执行此操作。Employee
Company
Employee
JPA的实体图似乎就是为了这个目的。
所以我在类上定义了一个:@NamedEntityGraph
Employee
@Entity
@NamedEntityGraph(name = "employeeOnly")
public class Employee {
@Id
private Integer id;
private String name;
private String surname;
@ManyToOne
private Company company;
//Getters & Setters
像这样:EmployeeRepository
public interface EmployeeRepository extends CrudRepository<Employee, Integer> {
@EntityGraph(value = "employeeOnly", type = EntityGraph.EntityGraphType.FETCH)
List<Employee> findByCompanyId(Integer companyId);
}
尽管使用了 ,但我可以在日志中看到 仍然通过休眠加载:@EntityGraph
Company
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=?
为什么?如何避免这种情况?