1

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?

Haris Hasan
  • 29,856
  • 10
  • 92
  • 122

2 Answers2

2

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 = ?
Genzotto
  • 1,954
  • 6
  • 26
  • 45
1

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());
fujy
  • 5,168
  • 5
  • 31
  • 50