Hibernate's Lazy strategy(2)

来源:互联网 发布:中国农产品出口数据 编辑:程序博客网 时间:2024/05/22 11:38
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?