Reputation: 30097
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?
Upvotes: 1
Views: 167
Reputation: 1974
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 = ?
Upvotes: 2
Reputation: 5264
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());
Upvotes: 1