Eager loading a lazy child collection

[亡魂溺海] 提交于 2019-12-11 06:36:43

问题


I have data model similar to this

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;
}

I have a JPQL query like this

select o from Office o where o.cafeteria.someThing = ?

Above query works fine but in one case I would like a query which could eagerly load all the chairs(o.cafeteria.chairs) as well. How should I modify query to eagerly fetch all chairs?


回答1:


Use fetch attribute in OneToMany annotation. You can map the same relationship as many times as you want:

class Cafeteria {
   @OneToMany(mappedBy="cafeteria")
   @LazyCollection(value=LazyCollectionOption.EXTRA)
   List<Chair> chairs;

   @OneToMany(fetch = FetchType.EAGER, mappedBy="cafeteria")
   List<Chair> eagerlyLoadedChairs;
}

And then you can use any of them:

// 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 = ?



回答2:


You have two options, either you change the fetch type from Lazy to Eager, but this will always load your List of Chair every time you load an object from Cafeteria.

like this:

@OneToMany(mappedBy="cafeteria", fetch=FetchType.EAGER)
@LazyCollection(value=LazyCollectionOption.FALSE)
List<Chair> chairs;

OR In your Service that call this query, after calling it, you simply load the Chair list in your specific use case, check more about Initializing Collections in Hibernate

Hibernate.initialize(cafeteria.getChairs());


来源:https://stackoverflow.com/questions/24573877/eager-loading-a-lazy-child-collection

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!