1. /*
  2. * Copyright 2002-2004 the original author or authors.
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. */
  16. package org.springframework.orm.hibernate.support;
  17. import javax.servlet.http.HttpServletRequest;
  18. import javax.servlet.http.HttpServletResponse;
  19. import net.sf.hibernate.FlushMode;
  20. import net.sf.hibernate.HibernateException;
  21. import net.sf.hibernate.Session;
  22. import org.springframework.dao.DataAccessException;
  23. import org.springframework.orm.hibernate.HibernateAccessor;
  24. import org.springframework.orm.hibernate.SessionFactoryUtils;
  25. import org.springframework.orm.hibernate.SessionHolder;
  26. import org.springframework.transaction.support.TransactionSynchronizationManager;
  27. import org.springframework.web.servlet.HandlerInterceptor;
  28. import org.springframework.web.servlet.ModelAndView;
  29. /**
  30. * Spring web HandlerInterceptor that binds a Hibernate Session to the thread for the
  31. * whole processing of the request. Intended for the "Open Session in View" pattern,
  32. * i.e. to allow for lazy loading in web views despite the original transactions
  33. * already being completed.
  34. *
  35. * <p>This interceptor works similar to the AOP HibernateInterceptor: It just makes
  36. * Hibernate Sessions available via the thread. It is suitable for non-transactional
  37. * execution but also for middle tier transactions via HibernateTransactionManager
  38. * or JtaTransactionManager. In the latter case, Sessions pre-bound by this interceptor
  39. * will automatically be used for the transactions and flushed accordingly.
  40. *
  41. * <p>In contrast to OpenSessionInViewFilter, this interceptor is set up in a Spring
  42. * application context and can thus take advantage of bean wiring. It derives from
  43. * HibernateAccessor to inherit common Hibernate configuration properties.
  44. *
  45. * <p><b>WARNING:</b> Applying this interceptor to existing logic can cause issues that
  46. * have not appeared before, through the use of a single Hibernate Session for the
  47. * processing of an entire request. In particular, the reassociation of persistent
  48. * objects with a Hibernate Session has to occur at the very beginning of request
  49. * processing, to avoid clashes will already loaded instances of the same objects.
  50. *
  51. * <p><b>NOTE</b>: This interceptor will by default not flush the Hibernate session,
  52. * as it assumes to be used in combination with middle tier transactions that care for
  53. * the flushing, or HibernateAccessors with flushMode FLUSH_EAGER. If you want this
  54. * interceptor to flush after the handler has been invoked but before view rendering,
  55. * set the flushMode of this interceptor to FLUSH_AUTO in such a scenario.
  56. *
  57. * @author Juergen Hoeller
  58. * @since 06.12.2003
  59. * @see #setFlushMode
  60. * @see OpenSessionInViewFilter
  61. * @see org.springframework.orm.hibernate.HibernateInterceptor
  62. * @see org.springframework.orm.hibernate.HibernateTransactionManager
  63. */
  64. public class OpenSessionInViewInterceptor extends HibernateAccessor implements HandlerInterceptor {
  65. /**
  66. * Create a new OpenSessionInViewInterceptor,
  67. * turning the default flushMode to FLUSH_NEVER.
  68. * @see #setFlushMode
  69. */
  70. public OpenSessionInViewInterceptor() {
  71. setFlushMode(FLUSH_NEVER);
  72. }
  73. /**
  74. * Opens a new Hibernate Session according to the settings of this HibernateAccessor
  75. * and binds in to the thread via TransactionSynchronizationManager.
  76. * @see org.springframework.orm.hibernate.SessionFactoryUtils#getSession
  77. * @see org.springframework.transaction.support.TransactionSynchronizationManager
  78. */
  79. public boolean preHandle(HttpServletRequest request, HttpServletResponse response,
  80. Object handler) throws DataAccessException {
  81. logger.debug("Opening Hibernate Session in OpenSessionInViewInterceptor");
  82. Session session = SessionFactoryUtils.getSession(getSessionFactory(), getEntityInterceptor(),
  83. getJdbcExceptionTranslator());
  84. if (getFlushMode() == FLUSH_NEVER) {
  85. session.setFlushMode(FlushMode.NEVER);
  86. }
  87. TransactionSynchronizationManager.bindResource(getSessionFactory(), new SessionHolder(session));
  88. return true;
  89. }
  90. /**
  91. * Flushes the Hibernate Session before view rendering, if necessary.
  92. * Set the flushMode of this HibernateAccessor to FLUSH_NEVER to avoid this extra flushing.
  93. * @see #setFlushMode
  94. */
  95. public void postHandle(HttpServletRequest request, HttpServletResponse response,
  96. Object handler, ModelAndView modelAndView) throws DataAccessException {
  97. logger.debug("Flushing Hibernate Session in OpenSessionInViewInterceptor");
  98. SessionHolder sessionHolder = (SessionHolder) TransactionSynchronizationManager.getResource(getSessionFactory());
  99. try {
  100. flushIfNecessary(sessionHolder.getSession(), false);
  101. }
  102. catch (HibernateException ex) {
  103. throw convertHibernateAccessException(ex);
  104. }
  105. }
  106. /**
  107. * Unbinds the Hibernate Session from the thread and closes it.
  108. * @see org.springframework.orm.hibernate.SessionFactoryUtils#closeSessionIfNecessary
  109. * @see org.springframework.transaction.support.TransactionSynchronizationManager
  110. */
  111. public void afterCompletion(HttpServletRequest request, HttpServletResponse response,
  112. Object handler, Exception ex) throws DataAccessException {
  113. SessionHolder sessionHolder = (SessionHolder) TransactionSynchronizationManager.unbindResource(getSessionFactory());
  114. logger.debug("Closing Hibernate Session in OpenSessionInViewInterceptor");
  115. SessionFactoryUtils.closeSessionIfNecessary(sessionHolder.getSession(), getSessionFactory());
  116. }
  117. }