OpenSessionInView詳解 關(guān)鍵字: Spring OpenSessionInView OpenSessionInViewFilter是Spring提供的一個(gè)針對(duì)Hibernate的一個(gè)支持類(lèi),其主要意思是在發(fā)起一個(gè)頁(yè)面請(qǐng)求時(shí)打開(kāi)Hibernate的Session,一直保持這個(gè)Session,直到這個(gè)請(qǐng)求結(jié)束,具體是通過(guò)一個(gè)Filter來(lái)實(shí)現(xiàn)的。 由于Hibernate引入了Lazy Load特性,使得脫離Hibernate的Session周期的對(duì)象如果再想通過(guò)getter方法取到其關(guān)聯(lián)對(duì)象的值,Hibernate會(huì)拋出一個(gè)LazyLoad的Exception。所以為了解決這個(gè)問(wèn)題,Spring引入了這個(gè)Filter,使得Hibernate的Session的生命周期變長(zhǎng)。 首先分析一下它的源碼,可以發(fā)現(xiàn),它所實(shí)現(xiàn)的功能其實(shí)比較簡(jiǎn)單: Java代碼
在上述代碼中,首先獲得SessionFactory,然后通過(guò)SessionFactory獲得一個(gè)Session。然后執(zhí)行真正的Action代碼,最后根據(jù)情況將Hibernate的Session進(jìn)行關(guān)閉。整個(gè)思路比較清晰。 注意,在這里有個(gè)2個(gè)Tips: 1)通過(guò)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ì)我們的開(kāi)發(fā)有幫助的結(jié)論: 1)如果使用了OpenSessionInView模式,那么Spring會(huì)幫助你管理Session的開(kāi)和關(guān),從而你在你的DAO中通過(guò)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)見(jiàn)過(guò)很多人在使用OpenSessionInView模式時(shí),都因?yàn)闆](méi)有正確配置事務(wù),導(dǎo)致了底層會(huì)拋出有關(guān)FlushMode.NEVER的異常。 OpenSessionInView這個(gè)模式使用比較簡(jiǎn)單,也成為了大家在Web開(kāi)發(fā)中經(jīng)常使用的方法,不過(guò)它有時(shí)候會(huì)帶來(lái)一些意想不到的問(wèn)題,這也是在開(kāi)發(fā)中需要注意的。 1. 在Struts+Spring+Hibernate環(huán)境中,由于配置的問(wèn)題導(dǎo)致的模式失效 這個(gè)問(wèn)題以前論壇曾經(jīng)討論過(guò),可以參考一下下面這個(gè)帖子: http://www.javaeye.com/topic/15057 2. OpenSessionInView的效率問(wèn)題 這個(gè)問(wèn)題也有人在論壇提出過(guò),Robbin曾經(jīng)做過(guò)具體的測(cè)試,可以具體參考一下下面這個(gè)帖子: http://www.javaeye.com/topic/17501 3. 由于使用了OpenSessionInView模式后造成了內(nèi)存和數(shù)據(jù)庫(kù)連接問(wèn)題 這個(gè)問(wèn)題是我在生產(chǎn)環(huán)境中碰到的一個(gè)問(wèn)題。由于使用了OpenSessionInView模式,Session的生命周期變得非常長(zhǎng)。雖然解決了Lazy Load的問(wèn)題,但是帶來(lái)的問(wèn)題就是Hibernate的一級(jí)緩存,也就是Session級(jí)別的緩存的生命周期會(huì)變得非常長(zhǎng),那么如果你在你的Service層做大批量的數(shù)據(jù)操作時(shí),其實(shí)這些數(shù)據(jù)會(huì)在緩存中保留一份,這是非常耗費(fèi)內(nèi)存的。還有一個(gè)數(shù)據(jù)庫(kù)連接的問(wèn)題,存在的原因在于由于數(shù)據(jù)庫(kù)的Connection是和Session綁在一起的,所以,Connection也會(huì)得不到及時(shí)的釋放。因而當(dāng)系統(tǒng)出現(xiàn)業(yè)務(wù)非常繁忙,而計(jì)算量又非常大的時(shí)候,往往數(shù)據(jù)連接池的連接數(shù)會(huì)不夠。這個(gè)問(wèn)題我至今非常頭痛,因?yàn)橛泻芏嗫蛻魧?duì)數(shù)據(jù)連接池的數(shù)量會(huì)有限制,不會(huì)給你無(wú)限制的增加下去。 4. 使用了OpenSessionInView模式以后取數(shù)據(jù)的事務(wù)問(wèn)題 在使用了OpenSessionInView以后,其實(shí)事務(wù)的生命周期比Session的生命周期來(lái)得短,就以為著,其實(shí)有相當(dāng)一部分的查詢是不被納入到事務(wù)的范圍內(nèi)的,此時(shí)是否會(huì)讀到臟數(shù)據(jù)?這個(gè)問(wèn)題我至今不敢確認(rèn),有經(jīng)驗(yàn)的朋友請(qǐng)指教一下。 最后提一下OpenSessionInView模式的一些替代方案,可以使用OpenSessionInViewInterceptor來(lái)代替這個(gè)Filter,此時(shí)可以使用Spring的AOP配置,將這個(gè)Interceptor配置到你所需要的層次上去。另外就是只能使用最古老的Hibernate.initialize()方法進(jìn)行初始化了。
1 SessionFactory sessionFactory = lookupSessionFactory(request);
2
3 Session session = null;
4
5 boolean participate = false;
6
7
8
9 if (isSingleSession()) {
10
11 // single session mode
12
13 if (TransactionSynchronizationManager.hasResource(sessionFactory)) {
14
15 // Do not modify the Session: just set the participate flag.
16
17 participate = true;
18
19 } else {
20
21 logger.debug("Opening single <A title=Hibernate href="http://www.google.cn/search?sbi=基金&amp;q=基金&amp;sbb=搜索&amp;sa=搜索&amp;client=pub-6430022987645146&amp;forid=1&amp;prog=aff&amp;ie=GB2312&amp;oe=GB2312&amp;hl=zh-CN " target=_blank>Hibernate</A> Session in OpenSessionInViewFilter");
22
23 session = getSession(sessionFactory);
24
25 TransactionSynchronizationManager.bindResource(sessionFactory, new SessionHolder(session));
26
27 }
28
29 } else {
30
31 // deferred close mode
32
33 if (SessionFactoryUtils.isDeferredCloseActive(sessionFactory)) {
34
35 // Do not modify deferred close: just set the participate flag.
36
37 participate = true;
38
39 } else {
40
41 SessionFactoryUtils.initDeferredClose(sessionFactory);
42
43 }
44
45 }
46
47
48
49 try {
50
51 filterChain.doFilter(request, response);
52
53 } finally {
54
55 if (!participate) {
56
57 if (isSingleSession()) {
58
59 // single session mode
60
61 TransactionSynchronizationManager.unbindResource(sessionFactory);
62
63 logger.debug("Closing single <A title=Hibernate href="http://www.google.cn/search?sbi=基金&amp;q=基金&amp;sbb=搜索&amp;sa=搜索&amp;client=pub-6430022987645146&amp;forid=1&amp;prog=aff&amp;ie=GB2312&amp;oe=GB2312&amp;hl=zh-CN " target=_blank>Hibernate</A> Session in OpenSessionInViewFilter");
64
65 closeSession(session, sessionFactory);
66
67 }else {
68
69 // deferred close mode
70
71 SessionFactoryUtils.processDeferredClose(sessionFactory);
72
73 }
74
75 }
76
77 }
78
79
80
81 SessionFactory sessionFactory = lookupSessionFactory(request);
82
83 Session session = null;
84
85 boolean participate = false;
86
87
88
89 if (isSingleSession()) {
90
91 // single session mode
92
93 if (TransactionSynchronizationManager.hasResource(sessionFactory)) {
94
95 // Do not modify the Session: just set the participate flag.
96
97 participate = true;
98
99 } else {
100
101 logger.debug("Opening single <A title=Hibernate href="http://www.google.cn/search?sbi=基金&amp;q=基金&amp;sbb=搜索&amp;sa=搜索&amp;client=pub-6430022987645146&amp;forid=1&amp;prog=aff&amp;ie=GB2312&amp;oe=GB2312&amp;hl=zh-CN " target=_blank>Hibernate</A> Session in OpenSessionInViewFilter");
102
103 session = getSession(sessionFactory);
104
105 TransactionSynchronizationManager.bindResource(sessionFactory, new SessionHolder(session));
106
107 }
108
109 } else {
110
111 // deferred close mode
112
113 if (SessionFactoryUtils.isDeferredCloseActive(sessionFactory)) {
114
115 // Do not modify deferred close: just set the participate flag.
116
117 participate = true;
118
119 } else {
120
121 SessionFactoryUtils.initDeferredClose(sessionFactory);
122
123 }
124
125 }
126
127
128
129 try {
130
131 filterChain.doFilter(request, response);
132
133 } finally {
134
135 if (!participate) {
136
137 if (isSingleSession()) {
138
139 // single session mode
140
141 TransactionSynchronizationManager.unbindResource(sessionFactory);
142
143 logger.debug("Closing single <A title=Hibernate href="http://www.google.cn/search?sbi=基金&amp;q=基金&amp;sbb=搜索&amp;sa=搜索&amp;client=pub-6430022987645146&amp;forid=1&amp;prog=aff&amp;ie=GB2312&amp;oe=GB2312&amp;hl=zh-CN " target=_blank>Hibernate</A> Session in OpenSessionInViewFilter");
144
145 closeSession(session, sessionFactory);
146
147 }else {
148
149 // deferred close mode
150
151 SessionFactoryUtils.processDeferredClose(sessionFactory);
152
153 }
154
155 }
156
157 }
2
3 Session session = null;
4
5 boolean participate = false;
6
7
8
9 if (isSingleSession()) {
10
11 // single session mode
12
13 if (TransactionSynchronizationManager.hasResource(sessionFactory)) {
14
15 // Do not modify the Session: just set the participate flag.
16
17 participate = true;
18
19 } else {
20
21 logger.debug("Opening single <A title=Hibernate href="http://www.google.cn/search?sbi=基金&amp;q=基金&amp;sbb=搜索&amp;sa=搜索&amp;client=pub-6430022987645146&amp;forid=1&amp;prog=aff&amp;ie=GB2312&amp;oe=GB2312&amp;hl=zh-CN " target=_blank>Hibernate</A> Session in OpenSessionInViewFilter");
22
23 session = getSession(sessionFactory);
24
25 TransactionSynchronizationManager.bindResource(sessionFactory, new SessionHolder(session));
26
27 }
28
29 } else {
30
31 // deferred close mode
32
33 if (SessionFactoryUtils.isDeferredCloseActive(sessionFactory)) {
34
35 // Do not modify deferred close: just set the participate flag.
36
37 participate = true;
38
39 } else {
40
41 SessionFactoryUtils.initDeferredClose(sessionFactory);
42
43 }
44
45 }
46
47
48
49 try {
50
51 filterChain.doFilter(request, response);
52
53 } finally {
54
55 if (!participate) {
56
57 if (isSingleSession()) {
58
59 // single session mode
60
61 TransactionSynchronizationManager.unbindResource(sessionFactory);
62
63 logger.debug("Closing single <A title=Hibernate href="http://www.google.cn/search?sbi=基金&amp;q=基金&amp;sbb=搜索&amp;sa=搜索&amp;client=pub-6430022987645146&amp;forid=1&amp;prog=aff&amp;ie=GB2312&amp;oe=GB2312&amp;hl=zh-CN " target=_blank>Hibernate</A> Session in OpenSessionInViewFilter");
64
65 closeSession(session, sessionFactory);
66
67 }else {
68
69 // deferred close mode
70
71 SessionFactoryUtils.processDeferredClose(sessionFactory);
72
73 }
74
75 }
76
77 }
78
79
80
81 SessionFactory sessionFactory = lookupSessionFactory(request);
82
83 Session session = null;
84
85 boolean participate = false;
86
87
88
89 if (isSingleSession()) {
90
91 // single session mode
92
93 if (TransactionSynchronizationManager.hasResource(sessionFactory)) {
94
95 // Do not modify the Session: just set the participate flag.
96
97 participate = true;
98
99 } else {
100
101 logger.debug("Opening single <A title=Hibernate href="http://www.google.cn/search?sbi=基金&amp;q=基金&amp;sbb=搜索&amp;sa=搜索&amp;client=pub-6430022987645146&amp;forid=1&amp;prog=aff&amp;ie=GB2312&amp;oe=GB2312&amp;hl=zh-CN " target=_blank>Hibernate</A> Session in OpenSessionInViewFilter");
102
103 session = getSession(sessionFactory);
104
105 TransactionSynchronizationManager.bindResource(sessionFactory, new SessionHolder(session));
106
107 }
108
109 } else {
110
111 // deferred close mode
112
113 if (SessionFactoryUtils.isDeferredCloseActive(sessionFactory)) {
114
115 // Do not modify deferred close: just set the participate flag.
116
117 participate = true;
118
119 } else {
120
121 SessionFactoryUtils.initDeferredClose(sessionFactory);
122
123 }
124
125 }
126
127
128
129 try {
130
131 filterChain.doFilter(request, response);
132
133 } finally {
134
135 if (!participate) {
136
137 if (isSingleSession()) {
138
139 // single session mode
140
141 TransactionSynchronizationManager.unbindResource(sessionFactory);
142
143 logger.debug("Closing single <A title=Hibernate href="http://www.google.cn/search?sbi=基金&amp;q=基金&amp;sbb=搜索&amp;sa=搜索&amp;client=pub-6430022987645146&amp;forid=1&amp;prog=aff&amp;ie=GB2312&amp;oe=GB2312&amp;hl=zh-CN " target=_blank>Hibernate</A> Session in OpenSessionInViewFilter");
144
145 closeSession(session, sessionFactory);
146
147 }else {
148
149 // deferred close mode
150
151 SessionFactoryUtils.processDeferredClose(sessionFactory);
152
153 }
154
155 }
156
157 }
在上述代碼中,首先獲得SessionFactory,然后通過(guò)SessionFactory獲得一個(gè)Session。然后執(zhí)行真正的Action代碼,最后根據(jù)情況將Hibernate的Session進(jìn)行關(guān)閉。整個(gè)思路比較清晰。 注意,在這里有個(gè)2個(gè)Tips: 1)通過(guò)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ì)我們的開(kāi)發(fā)有幫助的結(jié)論: 1)如果使用了OpenSessionInView模式,那么Spring會(huì)幫助你管理Session的開(kāi)和關(guān),從而你在你的DAO中通過(guò)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)見(jiàn)過(guò)很多人在使用OpenSessionInView模式時(shí),都因?yàn)闆](méi)有正確配置事務(wù),導(dǎo)致了底層會(huì)拋出有關(guān)FlushMode.NEVER的異常。 OpenSessionInView這個(gè)模式使用比較簡(jiǎn)單,也成為了大家在Web開(kāi)發(fā)中經(jīng)常使用的方法,不過(guò)它有時(shí)候會(huì)帶來(lái)一些意想不到的問(wèn)題,這也是在開(kāi)發(fā)中需要注意的。 1. 在Struts+Spring+Hibernate環(huán)境中,由于配置的問(wèn)題導(dǎo)致的模式失效 這個(gè)問(wèn)題以前論壇曾經(jīng)討論過(guò),可以參考一下下面這個(gè)帖子: http://www.javaeye.com/topic/15057 2. OpenSessionInView的效率問(wèn)題 這個(gè)問(wèn)題也有人在論壇提出過(guò),Robbin曾經(jīng)做過(guò)具體的測(cè)試,可以具體參考一下下面這個(gè)帖子: http://www.javaeye.com/topic/17501 3. 由于使用了OpenSessionInView模式后造成了內(nèi)存和數(shù)據(jù)庫(kù)連接問(wèn)題 這個(gè)問(wèn)題是我在生產(chǎn)環(huán)境中碰到的一個(gè)問(wèn)題。由于使用了OpenSessionInView模式,Session的生命周期變得非常長(zhǎng)。雖然解決了Lazy Load的問(wèn)題,但是帶來(lái)的問(wèn)題就是Hibernate的一級(jí)緩存,也就是Session級(jí)別的緩存的生命周期會(huì)變得非常長(zhǎng),那么如果你在你的Service層做大批量的數(shù)據(jù)操作時(shí),其實(shí)這些數(shù)據(jù)會(huì)在緩存中保留一份,這是非常耗費(fèi)內(nèi)存的。還有一個(gè)數(shù)據(jù)庫(kù)連接的問(wèn)題,存在的原因在于由于數(shù)據(jù)庫(kù)的Connection是和Session綁在一起的,所以,Connection也會(huì)得不到及時(shí)的釋放。因而當(dāng)系統(tǒng)出現(xiàn)業(yè)務(wù)非常繁忙,而計(jì)算量又非常大的時(shí)候,往往數(shù)據(jù)連接池的連接數(shù)會(huì)不夠。這個(gè)問(wèn)題我至今非常頭痛,因?yàn)橛泻芏嗫蛻魧?duì)數(shù)據(jù)連接池的數(shù)量會(huì)有限制,不會(huì)給你無(wú)限制的增加下去。 4. 使用了OpenSessionInView模式以后取數(shù)據(jù)的事務(wù)問(wèn)題 在使用了OpenSessionInView以后,其實(shí)事務(wù)的生命周期比Session的生命周期來(lái)得短,就以為著,其實(shí)有相當(dāng)一部分的查詢是不被納入到事務(wù)的范圍內(nèi)的,此時(shí)是否會(huì)讀到臟數(shù)據(jù)?這個(gè)問(wèn)題我至今不敢確認(rèn),有經(jīng)驗(yàn)的朋友請(qǐng)指教一下。 最后提一下OpenSessionInView模式的一些替代方案,可以使用OpenSessionInViewInterceptor來(lái)代替這個(gè)Filter,此時(shí)可以使用Spring的AOP配置,將這個(gè)Interceptor配置到你所需要的層次上去。另外就是只能使用最古老的Hibernate.initialize()方法進(jìn)行初始化了。