Tweak Hibernate Lazy Loading via @BatchSize

Hibernate @BatchSize annotation is a great way to increase performance when dealing with large result sets:

class Foo {
    @BatchSize(size = 100)
    Set<Bar> bars;

The annotation is often misunderstood. @BatchSize on collections is not related to the collections size. Instead it’s related to the number of uninitialized Foos contained in the current session.

List<Foo> foos = session.createQuery("from Foo").list();
for (Foo foo : foos) {
    // select bars for 100 foos at once:

So, when foos has a size of 100, all bars will be fetched with 1 SELECT instead of 100 SELECTs.

Read More