我有与此类似的数据模型
class Office
{
@ManyToOne
@JoinColumn(name = "cafeteria_id")
Cafeteria cafeteria;
}
class Cafeteria
{
@OneToMany(mappedBy="cafeteria")
@LazyCollection(value=LazyCollectionOption.EXTRA)
List<Chair> chairs;
}
class Chair
{
@ManyToOne
@JoinColumn(name = "cafeteria_id")
Cafeteria cafeteria;
}
我有这样的JPQL查询
select o from Office o where o.cafeteria.someThing = ?
上面的查询工作正常,但在一种情况下,我想查询一个可以同时加载所有椅子(o.cafeteria.chairs)的查询。我应该如何修改查询以热切地获取所有椅子?
最佳答案
在fetch
批注中使用OneToMany
属性。您可以根据需要映射多次相同的关系:
class Cafeteria {
@OneToMany(mappedBy="cafeteria")
@LazyCollection(value=LazyCollectionOption.EXTRA)
List<Chair> chairs;
@OneToMany(fetch = FetchType.EAGER, mappedBy="cafeteria")
List<Chair> eagerlyLoadedChairs;
}
然后您可以使用其中任何一个:
// Lazy loading
select o from Office o inner join o.cafeteria c inner join c.chairs ch where c.someThing = ?
// Eager loading
select o from Office o inner join o.cafeteria c inner join c.eagerlyLoadedChairsch where c.someThing = ?