4

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.

2 Answers 2

7
+50

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.

Sign up to request clarification or add additional context in comments.

2 Comments

that sounds like what I'm looking for. Can I enable/disable this profile between two transaction within a single session?
@iliaden Yes you can use Session#disableFetchProfile( profileName ) to disable that in the same session. You can also use Session#isFetchProfileEnabled( profileName ) to find out if a fetch profile is enabled or disabled.
0

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".

1 Comment

I'm aware that it helps resolving the N+1 problem. However, it overwrites the eager/lazy settings. My question is whether it is possible or not ofr these settings to co-exist and be set programmatically.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.