- 浏览: 114323 次
- 性别:
- 来自: 宁波
文章分类
最新评论
在没有使用Spring提供的Open Session In View情况下,因需要在service(or Dao)层里把session关闭,所以lazy loading 为true的话,要在应用层内把关系集合都初始化,如 company.getEmployees(),否则Hibernate抛session already closed Exception; Open Session In View提供了一种简便的方法,较好地解决了lazy loading问题.
它有两种配置方式OpenSessionInViewInterceptor和OpenSessionInViewFilter(具体参看SpringSide),功能相同,只是一个在web.xml配置,另一个在application.xml配置而已。
Open Session In View在request把session绑定到当前thread期间一直保持hibernate session在open状态,使session在request的整个期间都可以使用,如在View层里PO也可以lazy loading数据,如 ${ company.employees }。当View 层逻辑完成后,才会通过Filter的doFilter方法或Interceptor的postHandle方法自动关闭session。
OpenSessionInViewInterceptor配置
- <beans>
- <bean name="openSessionInViewInterceptor" class="org.springframework.orm.hibernate3.support.OpenSessionInViewInterceptor">
- <property name="sessionFactory">
- <ref bean="sessionFactory"/>
- </property>
- </bean>
- <bean id="urlMapping" class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
- <property name="interceptors">
- <list>
- <ref bean="openSessionInViewInterceptor"/>
- </list>
- </property>
- <property name="mappings">
- ...
- </property>
- </bean> ... </beans>
OpenSessionInViewFilter配置
- <web-app>
- ...
- <filter>
- <filter-name>hibernateFilter</filter-name>
- <filter-class> org.springframework.orm.hibernate3.support.OpenSessionInViewFilter </filter-class>
- <!-- singleSession默认为true,若设为false则等于没用OpenSessionInView -->
- <init-param>
- <param-name>singleSession</param-name>
- <param-value>true</param-value>
- </init-param>
- </filter> ... <filter-mapping>
- <filter-name>hibernateFilter</filter-name>
- <url-pattern>*.do</url-pattern>
- </filter-mapping> ... </web-app>
很多人在使用OpenSessionInView过程中提及一个错误:
org.springframework.dao.InvalidDataAccessApiUsageException: Write operations are not allowed in read-only mode (FlushMode.NEVER) - turn your Session into FlushMode.AUTO or remove 'readOnly' marker from transaction definition
看看OpenSessionInViewFilter里的几个方法
- protected void doFilterInternal(HttpServletRequest request,
- HttpServletResponse response,
- FilterChain filterChain) throws ServletException, IOException {
- SessionFactory sessionFactory = lookupSessionFactory();
- logger.debug("Opening Hibernate Session in OpenSessionInViewFilter");
- Session session = getSession(sessionFactory);
- TransactionSynchronizationManager.bindResource(
- sessionFactory, new SessionHolder(session));
- try {
- filterChain.doFilter(request, response);
- }
- finally {
- TransactionSynchronizationManager.unbindResource(sessionFactory);
- logger.debug("Closing Hibernate Session in OpenSessionInViewFilter");
- closeSession(session, sessionFactory);
- }
- }
- protected Session getSession(SessionFactory sessionFactory)
- throws DataAccessResourceFailureException {
- Session session = SessionFactoryUtils.getSession(sessionFactory, true);
- session.setFlushMode(FlushMode.NEVER);
- return session;
- }
- protected void closeSession(Session session,
- SessionFactory sessionFactory)throws CleanupFailureDataAccessException {
- SessionFactoryUtils.closeSessionIfNecessary(session, sessionFactory);
- }
关于绑定session的方式,通过看spring里TransactionSynchronizationManager的实现,发现:它维护一个 java.lang.ThreadLocal类型的resources,resources负责持有线程局部变量,这里resources持有的是一个 HashMap,通过TransactionSynchronizationManager.bindResource()方法在map里绑定和线程相关的所有变量到他们的标识上,包括如上所述的绑定在sessionFactory上的线程局部session。sessionHolder只不过是存放可以 hold一个session并可以和transtaction同步的容器。可以看到 OpenSessionInViewFilter在getSession的时候,会把获取回来的session的flush mode 设为FlushMode.NEVER。然后把该sessionFactory绑定到 TransactionSynchronizationManager,使request的整个过程都使用同一个session,在请求过后再接除该 sessionFactory的绑定,最后closeSessionIfNecessary根据该session是否已和transaction绑定来决定是否关闭session。绑定以后,就可以防止每次不会新开一个Session呢?看看HibernateDaoSupport的情况:
- public final void setSessionFactory(SessionFactory sessionFactory) {
- this.hibernateTemplate = new HibernateTemplate(sessionFactory);
- }
- rotected final HibernateTemplate getHibernateTemplate() {
- return hibernateTemplate;
我们的DAO将使用这个template进行操作.
- public abstract class BaseHibernateObjectDao
- extends HibernateDaoSupportimplements BaseObjectDao {
- protected BaseEntityObject getByClassId(final long id) {
- BaseEntityObject obj =(BaseEntityObject)getHibernateTemplate().execute(new HibernateCallback() {
- public Object doInHibernate(Session session)
- throws HibernateException{
- return session.get(getPersistentClass(),new Long(id));
- }
- }
- );
- return obj;
- }
- public void save(BaseEntityObject entity) {
- getHibernateTemplate().saveOrUpdate(entity);
- }
- public void remove(BaseEntityObject entity) {
- try {
- getHibernateTemplate().delete(entity);
- } catch (Exception e) {
- throw new FlexEnterpriseDataAccessException(e);
- }
- }
- public void refresh(final BaseEntityObject entity) {
- getHibernateTemplate().execute(new HibernateCallback(){
- public Object doInHibernate(Session session)
- throws HibernateException {
- session.refresh(entity);
- return color: #7f
发表评论
-
Open Session In View(转)
2010-12-04 21:58 1068英文原文:http://community.jboss.org ... -
Hibernate并发控制
2010-12-04 19:46 10063. 多个事务并发引起的问题:3.1. 第 ... -
servlet和filter的异同
2010-12-04 19:28 952以前总以为filter就是一种特殊servlet,所以他们 ... -
JavaScript,调用函数的5种方法
2010-11-28 16:16 878JavaScript,调用函数的5种方法 一次又一次的,我发现 ... -
IOC原理
2010-11-28 09:18 828IOC(inview of control)控制反转 ... -
Hibernate级联操作Cascade学之---delete
2010-11-27 10:06 938所在cascade,就是说我在更新一方的时候,可以根据这一 ... -
HTTP POST GET 本质区别详解
2010-11-27 09:47 827HTTP POST GET 本质区别详解 收藏 ... -
Hibernate二级缓存(转)
2010-11-27 09:38 766Hibernate二级缓存(转 ... -
加速你的Hibernate引擎(下)
2010-11-27 09:37 770加速你的Hibernate引擎(下) 文章分类:Ja ... -
加速你的Hibernate引擎(上)
2010-11-27 09:36 846加速你的Hibernate引擎(上) 文章分类:Ja ... -
spring Transaction Manager和hibernate session
2010-11-27 09:33 1038spring Transaction Manager ... -
浅析Spring提供的事务管理方法
2010-11-27 09:32 780浅析Spring提供的事务管理方法 2006-0 ... -
hibernate性能优化
2010-11-27 09:24 633转 hibernate性能优化 ... -
Hibernate 性能优化技巧
2010-11-27 09:23 725转 Hibernate 性能优化 ... -
Hibernate乐观锁实现之Timestamp
2010-11-27 09:21 847转 Hibernate乐观锁实现之Timestamp ... -
Hibernate乐观锁实现之Version
2010-11-27 09:21 802转 Hibernate乐观锁实现之Version ... -
Hibernate悲观锁定与乐观锁定区别
2010-11-27 09:20 673转 Hibernate悲观锁定 ... -
Hibernate二级缓存 ---- 最佳实践
2010-11-27 09:19 878转 Hibernate二级缓存 ---- 最佳实践 ... -
Spring如何与struts2结合
2010-11-22 12:34 9304.Spring如何与struts2结合 关键字: ... -
struts2 iterator
2010-11-21 21:12 894struts2的s:iterator 可以遍历 数据栈里面 ...
相关推荐
Open Session in View模式.PPT
struts2+hibernate3 做的小项目 使用了struts2插件实现pen session in view
在没有使用Spring提供的Open Session In View情况下,因需要在service(or Dao)层里把session关闭,所以lazy loading 为true的话,要在应用层内把关系集合都初始化,如 company.getEmployees(),否则Hibernate抛...
使用Spring提供的Open Session In View而引起Write operations are not allowed in read-only mode (FlushMode.NEVER) 错误解决
SSH整合概述 应用IoC进行整合 应用AOP进行整合 Open Session In View模式
为了练手培训,给大家准备的 Open Session In View 的简单例子,纯代码,大家可以参考,其中主要说了六部分内容: 1.通过接口编程 2.通过spring注入dao到 action 3.通过 open session in view filter 支持 延迟加载...
View detailed session, code lab, and speaker information, including speaker bios, photos, and Google+ profiles +1 sessions right from the app Participate in public #io12 conversations on Google+ Guide...
Open Session; Close Session; Secure Session; Manage Cookie; Block User by Cookie; Create Google Chart; Curl Get Contents; Fetch Wiki Page; Fetch Flickr Stream; Get Yahoo! Answers; Search Yahoo!; Get ...
You can open multiple files in the Open dialogue box, by holding down the Shift or Ctrl key down as you select each file. You can press ESC to return from Full Screen mode to normal mode.
它演示了MvC 、 SoC 、 IoC 、 DAO 、 Service layer和Open Session in View模式以及其他 J2EE 最佳实践。 该模板可以轻松扩展为功能齐全的基于 Wicket 的 Web 应用程序。 用法 该模板使用 maven 并在 Tomcat7 上...
In this tutorial, we'll cover some of the basics of Unicode-encoded text and Unicode files, and how to view and manipulate it in UltraEdit. Search and delete lines found UEStudio and UltraEdit provide...
* Describe Window now also shows the view comments in the header * Export Tables would change nls_date_format in single session mode and dual session mode * Auto Replace now supports Undo to continue...
- fixed bug with URLs in Open Document Text and Open Document Spreadsheet exports - fixed format string in XLS OLE export - fixed format string in XLS BIFF8 export - fixed output of the check boxes ...
Encodes the specified URL by including the session ID in it, or, if encoding is not needed, returns the URL unchanged. -------------------------------------------------------------------------------...
* Multi-select files in project-view (when "double-click to open" is configured in Environment Settings) * Resource files are treated as ordinary files now * Updates in "Project Options/Files" code * ...
更新的内容包含: Version 10.8 (2018-07-07) Bugfix: fixed the error message which occured when running the graphical package manager...引用地址:http://www.open-open.com/lib/view/open1437704662490.html
It is stored in CBCGPGridCtrl::m_PrintParams::m_pageInfo member and in CPrintInfo::m_lpUserData member of the CPrintInfo object used while printing at the current print session. Added an option to ...
File encoding of open files is now stored in the session Build Systems may define a cancel command using the "cancel" key Syntax: Added clear_scopes directive, to give more control over the generated ...
Triggers can now be created in the context of a table or view Folders added for Primary, Unique and Foreign key constraints for views Search Bar enhancements A new Search in files option allows you ...
Added a statusbar to the hexview in memoryview Pointerscan for value scans now add the results to the overflow queue Opening a file and changing bytes do not change them to the file anymore (you need ...