iliaden
iliaden

Reputation: 3889

Hibernate Batch Fetching to Lazy Loading

Currently, I observe in hbernate3, the following behavior. if I have @BatchSize(size=5) set, then hibernate will fetch 5 subsets of the mapped type in one SQL query.

If I have .setFetchMode( "set", FetchMode.JOIN ); , then hibernate will eagerly fetch all the subsets of the mapped type ina single SQL query.

However, when I set .setFetchMode( "commands", FetchMode.SELECT ); , then hibernate still uses batch fetching, and not lazy fetching.

Is there a way to force hibernate to use lazy fetching when @BatchSize is set?

The same question applies to when @Fetch(FetchMode.SUBSELECT) is set.

Upvotes: 4

Views: 3404

Answers (2)

user18943
user18943

Reputation: 747

If you want to override these settings programmatically, you can consider using @FetchProfile. Just create a @FetchProfile for an entity:

@FetchProfiles({
  @FetchProfile(name = "profileName", fetchOverrides = {
    @FetchProfile.FetchOverride(entity = YourEntity.class, 
                                association = "anAssociation", 
                                mode = FetchMode.JOIN),
...
}) })
and enable that profile in your service/repository method like:

session.enableFetchProfile( "profileName" );
and your customized fetch settings will work for that session.

Upvotes: 7

alex.b
alex.b

Reputation: 1528

Sorry, but @BatchSize is used to solve "N+1 problem" but not to ask Hibernate load entities eagerly or lazy. Try to search by keywords: "Hibernate, n+1 problem, batch size".

Upvotes: 0

Related Questions