Normal 0 7.8 磅 0 2 false false false MicrosoftInternetExplorer4 /* Style Definitions */ table.MsoNormalTable{mso-style-name:普通表格;mso-tstyle-rowband-size:0;mso-tstyle-colband-size:0;mso-style-noshow:yes;mso-style-parent:"";mso-padding-alt:0cm 5.4pt 0cm 5.4pt;mso-para-margin:0cm;mso-para-margin-bottom:.0001pt;mso-pagination:widow-orphan;font-size:10.0pt;font-family:"Times New Roman";mso-fareast-font-family:"Times New Roman";mso-ansi-language:#0400;mso-fareast-language:#0400;mso-bidi-language:#0400;}
spring +struts + hibernate 時事務配置注意的問題
當 spring 裡配置有 < aop:aspectj-autoproxy /> 也就是對 spring 裡配置的 bean 組建代理程式( java 反射機制和動態代理),以便切面通知
當連接點(方法的執行)退出時,自動代理的對象將會關閉 session ,也就是不能初始化代理,會出現這樣的情況比如: hibernate 裡設定物件關聯,當在連接點載入了一個對象,然後在連接點之後訪問另一個對象時(除 ID ), spring 就會拋出:不能初始化代理, no session ,
為瞭解決這樣的問題, spring 引入了 openSessionInViewFilter 過濾器,在 web.xml 配置如下:
< filter >
< filter-name > openSessionInViewFilter </ filter-name >
< filter-class >
org.springframework.orm.hibernate3.support.OpenSessionInViewFilter
</ filter-class >
< init-param >
< param-name > singleSession </ param-name >
< param-value > false </ param-value >
</ init-param >
</ filter >
< filter-mapping >
< filter-name > openSessionInViewFilter </ filter-name >
< url-pattern > /* </ url-pattern >
</ filter-mapping >
注意其中的:
< param-name > singleSession </ param-name >
< param-value > false </ param-value >
配置,預設這個設定是 true, 也就是一個 request 的開始到一個 response 的結束,只用一個 session 來處理 , 而我們配置的切面,只是到 service 層,並沒有到 aciton( 注意,我們的 action 通常也是配置為 spring 的 bean), 而在 service 層動態代理已經是關閉了,這樣,當你要訪問對象關聯裡其他對象的屬性時, spring 同樣會拋出:不能初始化代理, no session ,這樣我們只要把上面的 true 改為 false ,當訪問關聯對象時, spring 會開啟新的一個 session 來處理,這樣也不會對我們的 service 層裡的事務造成影響,我們的 service 同樣還是使用相同的 session,
我在 hibernate.properties 裡的配置是:
hibernate.connection.release_mode after_transaction