Eager Loading usig Batch Fetching

890 Views Asked by At

Is it possible to coerce JPA implemented by Hibernate into doing eager loading using Batch fetching?

You are probably wondering why I want to do such a strange thing, so let me explain.

We have two Entities A and B. There is a many to 1 relationship from A to B.

I want to load A entities with a search, and I want to have them fully loaded before they get returned from the repository.

But since there are lots of A's and very few B's all the (relevant) B's will be in the second level cache. Therefore I want to avoid getting all the B's every time from the database.

1

There are 1 best solutions below

2
V G On

As I understand your problem, a solution would be to use a NamedQuery with a FETCH instruction in a NamedQuery:

SELECT DISTINCT B LEFT JOIN FETCH B.a A//will return fully loaded B instances

If you want to specify the Batch Size, you can use the @BatchSize in Hibernate (not JPA). Check this link for an example.