1。建議使用Hiberante進行Session和Transaction的管理
??? 將需要進行事務的多個原子DAO設置到Service里,在Service層進行事務控制和會話控制
??? 設置一個基礎的dao,即baseDAO 且繼承之HibernateDaoSupport,而業務對象原子DAO,持有一個baseDAO的引用,通過setter注射設置到業務DAO中
??? 多個原子DAO,通過setter注射到Service層。
2。在顯示層,一對多顯示時,提示Session關閉的問題
??? 兩個解決方法:
??? 1)在one-to-many設置lazy=false,即不延遲加載子對象,但這樣可能會帶來性能的問題,特別是父子關系模型是樹狀結構時。
???
2)使用Hibernate提供的openSessiojnInView技術,即在視圖層開啟和關閉Session,在service層進行
Transaction管理,這個較為簡單,只需要設置一個filter即可,在web.xml中配置
<filter> ??<filter-name>hibernateFilter</filter-name> ??<filter-class>org.springframework.orm.hibernate.support.OpenSessionInViewFilter</filter-class> ?</filter> ?<filter-mapping> ??<filter-name>hibernateFilter</filter-name> ??<url-pattern>/*</url-pattern> ?</filter-mapping> |
需要注意的是,OpenSessionInViewFilter在調用過程中,需要引用Spring的ApplicationContext,而該 對象實例必須是保存在ServletContext中的,因此需要在web.xml中處始化Spring的環境,增加配置如下:
?<context-param> ???????????? <param-name>contextConfigLocation</param-name> ???????????? <param-value>/WEB-INF/spring/applicationContext-hibernate.xml</param-value> ?????? ?</context-param> ???? <servlet> |
其中
<servlet-name>context</servlet-name> ???????????? <servlet-class>org.springframework.web.context.ContextLoaderServlet</servlet-class> ???????????? <load-on-startup>1</load-on-startup> ??? ?</servlet> |
表示在啟動時,進行Spring環境的處始化,因此以后如果要引用Spring中的某個bean實例
如下代碼即可
org.springframework.context.ApplicationContext ctx = (org.springframework.context.ApplicationContext)application.getAttribute(org.springframework.web.context.WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE); |
然后調用ctx.getBean返回bean實例
Spring不只是AOP和IOC,更提供了大量的可重用技術,譬如request中的重設編碼,Spring提供了相應的Filter:org.springframework.web.filter.CharacterEncodingFilter 通過直接配置,即可解決Web應用中POST的中文亂碼問題,JMS的org.springframework.jms 包? JavaMail的org.springframework.mail包等等,更多的,請參看Spring的reference,
Spring能改善現有代碼結構,大量的減少hard code,加快開發進度;
一直有一種感覺:系統的構建是類似的搭積木