开发者

Hibernate Batch Fetching to Lazy Loading

开发者 https://www.devze.com 2023-03-12 06:21 出处:网络
Currently, I observe in hbernate3, the following behavi开发者_如何学Goor. if I have @BatchSize(size=5)

Currently, I observe in hbernate3, the following behavi开发者_如何学Goor. 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.


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.


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

0

精彩评论

暂无评论...
验证码 换一张
取 消