Hibernate's Lazy strategy(2)

The lazy strategy can be found anywhere in Hibernate.

The idea comes from that: It only gives you what you want.

So, In such situation : A user has many books, even we eagerly fetch the user, the books are still placeholders by default.

However, there is a problem, when I really want the books after I get the user every time. By default, the books will only be fetched when I process all of them. So it produces the n + 1 selects problem: after select 1 user, n more selects needed to fetch the books.

I such situation, more strategies to improve that problem.

1 batch select strategy. batch-size added to the configuration:
<set name="books" inverse="true" batch-size="10">...</set>
Now, when one book needed in the books, then another 9 books will be pre-fetched( 9 more books also fetched in one sql)
So there is total n / 10 + 1 selects needed.
This situation can be described like that: If I want to process one book of the user, it is likely that another books (not all)  also will be processed.
2 subselect strategy. This strategy is like earlier strategy, and be different in that: is a book is needed, then all books pre-fetched with that book); So there are two sql needed.

 1 Eagerly fetch. Above strategies occur when the book needed, but if books are needed when the user fetched, then this strategy can use just one sql.  following configuration may be needed:
<set name="books" inverse="true" fetch="join">...</set>
Now the sql fetching the user looks like that:
 select u.* from users u left outer join books b on b.user_id = u.id  where ....

It looks like good, just configuration needed, and hibernate does the left things.
But, it is not the end of story.

The fetch plan defined in configuration is the global strategy, so every selects will use that plan. But, actually, we are not sure only one plan is enough all the time. Maybe, we get the user, but we don't care the books; Or, We really care the books he read. Who can ensure that?
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值