2

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.

veer7
  • 20,074
  • 9
  • 46
  • 74
Jens Schauder
  • 77,657
  • 34
  • 181
  • 348

1 Answers1

0

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.

V G
  • 18,822
  • 6
  • 51
  • 89
  • but in order to load the B instances, it will use a join, thereby bypassing the second level cache, right? – Jens Schauder Mar 12 '14 at 11:13
  • IMHO yes, as it is the case with any NamedQuery (if the query results were not cached!). But you can use `@BatchSize` without NamedQueries. – V G Mar 13 '14 at 09:40