0

I have got many OneToMany relationships that needs to be loaded eagerly in most cases like this:

@OneToMany(fetch = FetchType.EAGER, mappedBy = "bar")
@Fetch(FetchMode.SELECT)
@BatchSize(size = 10)

However, I need, in a very few cases, to change it in hibernate criteria to lazy load (still select and batch). But I do not know how to do it. When I try solution from here -

criteria.setFetchMode("propertyName", FetchMode.SELECT);

it still loads eagerly.

My criteria looks something like this now:

Criteria criteria = sessionFactory.getCurrentSession().createCriteria(Bar.class);
criteria.add(Restrictions.eq("valid", true));
criteria.add(Restrictions.idEq(barId));
Bar result = (Bar) criteria.uniqueResult();

Here is entity, just for illustration purposes...

@Entity
@Table(name = "BAR", schema = "UD")
public class Bar {
    private List<Foo> foos;

    @OneToMany(fetch = FetchType.EAGER, mappedBy = "bar")
    @Fetch(FetchMode.SELECT)
    @BatchSize(size = 10)
    public List<Foo> getFoos() {
        return foos;
    }
}

I am using Hibernate 5.1.10.Final

stove
  • 556
  • 6
  • 24

1 Answers1

0

I don't know is it possible to do on-demand fetching but there is one technique available for this, you can use fetch Bar object using constructor inside custom query:

@Query("SELECT new BAR( <add other required fields except FOOs> ) from BAR")

Note: This is different from LAZY loading. If you need Foo later than you have to make DB call again.

  • Hi, thanks for the interesting tip. I do need it later sometimes. Moreover the entity is really huge, with lot of such relations (nothing I can do about it), and creating such query would be very unclear. Right now, I am actually using another entity for the same table with different annotations, but I would prefer to have that option to switch it somehow more easily in criteria. Thanks. – stove Apr 17 '20 at 08:24