为自己学习 LAZY 加载,我认为该集合应该为 NULL,直到它被明确要求加载。
这是餐厅实体的示例(为简洁起见,省略了方法,只留下了 toString)
public class Restaurant extends AbstractNamedEntity {
String address;
@OneToMany(mappedBy = "restaurant", cascade = CascadeType.ALL, orphanRemoval = true)
@JsonManagedReference
private List<Dish> dishes;
@OneToMany(mappedBy = "restaurant", cascade = CascadeType.ALL, orphanRemoval = true)
@JsonManagedReference
private List<Vote> votes;
@Override
public String toString() {
return "Restaurant{" +
"address='" + address + '\'' +
", dishes=" + dishes +
", votes=" + votes +
'}';
}
}
首先,我加载 Vote 对象,该对象本身具有到 Restaurant 的链接,并获取它。那些。
Vote vote = voteRepository.getById(1);
Restaurant restaurant = Vote.getRestaurant();
System.out.println(restaurant);
这出来了
Restaurant{address='Эспланада, 2а', dishes=[Dish{price=80.0, dateAdded=2021-08-13 };, Dish{price=69.0, dateAdded=2021-08-13 };], votes=[ voteDate=2021-08-13, user=restaurant.entity.User@22}]}
那些。尽管默认获取类型是 @OneToMany 惰性,但所有集合都已加载。为什么?在我明确执行 restaurant.getDishes() 之前,它们应该为 NULL 是不是很懒惰。
好的,假设这是从另一个对象中获取对象的功能,该对象具有对它的引用。但是如果你直接写
Restaurant restaurant = restaurantRepository.getById(1);
System.out.println(restaurant);
那么结果不会改变。所有集合都将使用 System.out.println() 加载。我将非常感谢任何能够清楚地解释为什么会这样的人。
PS 即使明确指定了 fetchType,结果也不会改变。
因为 LAZY 加载在您访问列表后立即开始加载实体。你在方法中做到这一点
toString()