OpenSessionInView詳解(面試時(shí)常會(huì)問到的問題)
OpenSessionInViewFilter是Spring提供的一個(gè)針對(duì)Hibernate的一個(gè)支持類,其主要意思是在發(fā)起一個(gè)頁(yè)面請(qǐng)求時(shí)打開Hibernate的Session,一直保持這個(gè)Session,直到這個(gè)請(qǐng)求結(jié)束,具體是通過一個(gè)Filter來(lái)實(shí)現(xiàn)的。由于Hibernate引入了Lazy Load特性,使得脫離Hibernate的Session周期的對(duì)象如果再想通過getter方法取到其關(guān)聯(lián)對(duì)象的值,Hibernate會(huì)拋出一個(gè)LazyLoad的Exception。所以為了解決這個(gè)問題,Spring引入了這個(gè)Filter,使得Hibernate的Session的生命周期變長(zhǎng)。
首先分析一下它的源碼,可以發(fā)現(xiàn),它所實(shí)現(xiàn)的功能其實(shí)比較簡(jiǎn)單:
Java代碼
1. SessionFactory sessionFactory = lookupSessionFactory(request);
2. Session session = null;
3. boolean participate = false;
4.
5. if (isSingleSession()) {
6. // single session mode
7. if (TransactionSynchronizationManager.hasResource(sessionFactory)) {
8. // Do not modify the Session: just set the participate flag.
9. participate = true;
10. } else {
11. logger.debug("Opening single Hibernate Session in OpenSessionInViewFilter");
12. session = getSession(sessionFactory);
13. TransactionSynchronizationManager.bindResource(sessionFactory, new SessionHolder(session));
14. }
15. } else {
16. // deferred close mode
17. if (SessionFactoryUtils.isDeferredCloseActive(sessionFactory)) {
18. // Do not modify deferred close: just set the participate flag.
19. participate = true;
20. } else {
21. SessionFactoryUtils.initDeferredClose(sessionFactory);
22. }
23. }
24.
25. try {
26. filterChain.doFilter(request, response);
27. } finally {
28. if (!participate) {
29. if (isSingleSession()) {
30. // single session mode
31. TransactionSynchronizationManager.unbindResource(sessionFactory);
32. logger.debug("Closing single Hibernate Session in OpenSessionInViewFilter");
33. closeSession(session, sessionFactory);
34. }else {
35. // deferred close mode
36. SessionFactoryUtils.processDeferredClose(sessionFactory);
37. }
38. }
39. }
2. Session session = null;
3. boolean participate = false;
4.
5. if (isSingleSession()) {
6. // single session mode
7. if (TransactionSynchronizationManager.hasResource(sessionFactory)) {
8. // Do not modify the Session: just set the participate flag.
9. participate = true;
10. } else {
11. logger.debug("Opening single Hibernate Session in OpenSessionInViewFilter");
12. session = getSession(sessionFactory);
13. TransactionSynchronizationManager.bindResource(sessionFactory, new SessionHolder(session));
14. }
15. } else {
16. // deferred close mode
17. if (SessionFactoryUtils.isDeferredCloseActive(sessionFactory)) {
18. // Do not modify deferred close: just set the participate flag.
19. participate = true;
20. } else {
21. SessionFactoryUtils.initDeferredClose(sessionFactory);
22. }
23. }
24.
25. try {
26. filterChain.doFilter(request, response);
27. } finally {
28. if (!participate) {
29. if (isSingleSession()) {
30. // single session mode
31. TransactionSynchronizationManager.unbindResource(sessionFactory);
32. logger.debug("Closing single Hibernate Session in OpenSessionInViewFilter");
33. closeSession(session, sessionFactory);
34. }else {
35. // deferred close mode
36. SessionFactoryUtils.processDeferredClose(sessionFactory);
37. }
38. }
39. }
1 SessionFactory sessionFactory = lookupSessionFactory(request);
2 Session session = null;
3 boolean participate = false;
4
5 if (isSingleSession()) {
6 // single session mode
7 if (TransactionSynchronizationManager.hasResource(sessionFactory)) {
8 // Do not modify the Session: just set the participate flag.
9 participate = true;
10 } else {
11 logger.debug("Opening single Hibernate Session in OpenSessionInViewFilter");
12 session = getSession(sessionFactory);
13 TransactionSynchronizationManager.bindResource(sessionFactory, new SessionHolder(session));
14 }
15 } else {
16 // deferred close mode
17 if (SessionFactoryUtils.isDeferredCloseActive(sessionFactory)) {
18 // Do not modify deferred close: just set the participate flag.
19 participate = true;
20 } else {
21 SessionFactoryUtils.initDeferredClose(sessionFactory);
22 }
23 }
24
25 try {
26 filterChain.doFilter(request, response);
27 } finally {
28 if (!participate) {
29 if (isSingleSession()) {
30 // single session mode
31 TransactionSynchronizationManager.unbindResource(sessionFactory);
32 logger.debug("Closing single Hibernate Session in OpenSessionInViewFilter");
33 closeSession(session, sessionFactory);
34 }else {
35 // deferred close mode
36 SessionFactoryUtils.processDeferredClose(sessionFactory);
37 }
38 }
39 }
2 Session session = null;
3 boolean participate = false;
4
5 if (isSingleSession()) {
6 // single session mode
7 if (TransactionSynchronizationManager.hasResource(sessionFactory)) {
8 // Do not modify the Session: just set the participate flag.
9 participate = true;
10 } else {
11 logger.debug("Opening single Hibernate Session in OpenSessionInViewFilter");
12 session = getSession(sessionFactory);
13 TransactionSynchronizationManager.bindResource(sessionFactory, new SessionHolder(session));
14 }
15 } else {
16 // deferred close mode
17 if (SessionFactoryUtils.isDeferredCloseActive(sessionFactory)) {
18 // Do not modify deferred close: just set the participate flag.
19 participate = true;
20 } else {
21 SessionFactoryUtils.initDeferredClose(sessionFactory);
22 }
23 }
24
25 try {
26 filterChain.doFilter(request, response);
27 } finally {
28 if (!participate) {
29 if (isSingleSession()) {
30 // single session mode
31 TransactionSynchronizationManager.unbindResource(sessionFactory);
32 logger.debug("Closing single Hibernate Session in OpenSessionInViewFilter");
33 closeSession(session, sessionFactory);
34 }else {
35 // deferred close mode
36 SessionFactoryUtils.processDeferredClose(sessionFactory);
37 }
38 }
39 }
在上述代碼中,首先獲得SessionFactory,然后通過SessionFactory獲得一個(gè)Session。然后執(zhí)行真正的Action代碼,最后根據(jù)情況將Hibernate的Session進(jìn)行關(guān)閉。整個(gè)思路比較清晰。
注意,在這里有個(gè)2個(gè)Tips:
1)通過getSession()獲得的這個(gè)Session做了一次
session.setFlushMode(FlushMode.NEVER); 有關(guān)FlushMode可以參考一下這篇文章。http://www2.matrix.org.cn/resource/article/2006-10-08/Hibernate+FlushMode+NEVER_312bca85-5699-11db-91a0-d98dff0aec60.html
2)Spring對(duì)拿到的Session做了一次綁定到當(dāng)前線程的做法,使得這個(gè)Session是線程安全的。
從上述代碼其實(shí)可以得到一些對(duì)我們的開發(fā)有幫助的結(jié)論:
1)如果使用了OpenSessionInView模式,那么Spring會(huì)幫助你管理Session的開和關(guān),從而你在你的DAO中通過HibernateDaoSupport拿到的getSession()方法,都是綁定到當(dāng)前線程的線程安全的Session,即拿即用,最后會(huì)由Filter統(tǒng)一關(guān)閉。
2)由于拿到的Hibernate的Session被設(shè)置了session.setFlushMode(FlushMode.NEVER); 所以,除非你直接調(diào)用session.flush(),否則Hibernate session無(wú)論何時(shí)也不會(huì)flush任何的狀態(tài)變化到數(shù)據(jù)庫(kù)。因此,數(shù)據(jù)庫(kù)事務(wù)的配置非常重要。(我們知道,在調(diào)用org.hibernate.Transaction.commit()的時(shí)候會(huì)觸發(fā)session.flush())我曾經(jīng)見過很多人在使用OpenSessionInView模式時(shí),都因?yàn)闆]有正確配置事務(wù),導(dǎo)致了底層會(huì)拋出有關(guān)FlushMode.NEVER的異常。
OpenSessionInView這個(gè)模式使用比較簡(jiǎn)單,也成為了大家在Web開發(fā)中經(jīng)常使用的方法,不過它有時(shí)候會(huì)帶來(lái)一些意想不到的問題,這也是在開發(fā)中需要注意的。
1. 在Struts+Spring+Hibernate環(huán)境中,由于配置的問題導(dǎo)致的模式失效
這個(gè)問題以前論壇曾經(jīng)討論過,可以參考一下下面這個(gè)帖子:
http://www.javaeye.com/topic/15057
2. OpenSessionInView的效率問題
這個(gè)問題也有人在論壇提出過,Robbin曾經(jīng)做過具體的測(cè)試,可以具體參考一下下面這個(gè)帖子:
http://www.javaeye.com/topic/17501
3. 由于使用了OpenSessionInView模式后造成了內(nèi)存和數(shù)據(jù)庫(kù)連接問題
這個(gè)問題是我在生產(chǎn)環(huán)境中碰到的一個(gè)問題。由于使用了OpenSessionInView模式,Session的生命周期變得非常長(zhǎng)。雖然解決了Lazy Load的問題,但是帶來(lái)的問題就是Hibernate的一級(jí)緩存,也就是Session級(jí)別的緩存的生命周期會(huì)變得非常長(zhǎng),那么如果你在你的Service層做大批量的數(shù)據(jù)操作時(shí),其實(shí)這些數(shù)據(jù)會(huì)在緩存中保留一份,這是非常耗費(fèi)內(nèi)存的。還有一個(gè)數(shù)據(jù)庫(kù)連接的問題,存在的原因在于由于數(shù)據(jù)庫(kù)的Connection是和Session綁在一起的,所以,Connection也會(huì)得不到及時(shí)的釋放。因而當(dāng)系統(tǒng)出現(xiàn)業(yè)務(wù)非常繁忙,而計(jì)算量又非常大的時(shí)候,往往數(shù)據(jù)連接池的連接數(shù)會(huì)不夠。這個(gè)問題我至今非常頭痛,因?yàn)橛泻芏嗫蛻魧?duì)數(shù)據(jù)連接池的數(shù)量會(huì)有限制,不會(huì)給你無(wú)限制的增加下去。
4. 使用了OpenSessionInView模式以后取數(shù)據(jù)的事務(wù)問題
在使用了OpenSessionInView以后,其實(shí)事務(wù)的生命周期比Session的生命周期來(lái)得短,就以為著,其實(shí)有相當(dāng)一部分的查詢是不被納入到事務(wù)的范圍內(nèi)的,此時(shí)是否會(huì)讀到臟數(shù)據(jù)?這個(gè)問題我至今不敢確認(rèn),有經(jīng)驗(yàn)的朋友請(qǐng)指教一下。
最后提一下OpenSessionInView模式的一些替代方案,可以使用OpenSessionInViewInterceptor來(lái)代替這個(gè)Filter,此時(shí)可以使用Spring的AOP配置,將這個(gè)Interceptor配置到你所需要的層次上去。另外就是只能使用最古老的Hibernate.initialize()方法進(jìn)行初始化了。
posted on 2009-11-24 11:13 MichaelLee 閱讀(573) 評(píng)論(0) 編輯 收藏 所屬分類: Spring