- 浏览: 3565 次
- 性别:
- 来自: 上海
最新评论
原文地址:http://blog.csdn.net/aspdao/article/details/5663347
从书上我了解到Session接口是Hibernate向应用程序提供的操纵数据库的最主要接口,它提供了基本的保存、更新、删除和加载Java对象的方法。Session具有一个缓存,位于缓存中的对象成为持久化对象,它和数据库中的相关记录对应,Session能够在某些时间点,按照缓存中对象的变化来执行相关的SQL语句,来同步更新数据库,这一过程叫清理缓存。
Hibernate把对象分为4种状态:持久化状态、临时状态、游离状态和删除状态。
- 临时状态:刚用new语句创建,还能没有被持久化,并且不处于Session的缓存中。处于临时状态的Java对象被称为临时对象。
- 持久化状态:已经被持久化,并且加入到Session的缓存中。处于持久化状态的Java对象被称为持久化对象。
- 删除状态:不再处于Session的缓存中,并且Session已经计划将其从数据库中删除。处与删除状态的对象被称为删除对象。
- 游离状态:已经被持久化,但不再处于Session的缓存中。处于游离状态的Java对象被称为游离对象。
在其他文章中找到的图片,很直观。
废话少说,切入正题,在开发SSH项目时,其实并不直接接触到Hibernate的Session,正常的步骤是,先搭建SSH框架,之后设计数据库,再根据数据库逆向工程生成相应的Bean和DAO,接下来根据具体需要将DAO封装成Service供业务逻辑层使用,至始至终都没有显式的创建Session对象,也没有手动关闭它,但是no session or session closed 却是最常遇到的问题。其实在逆向工程自动生成的***DAO.java中的每个方法,save();delete();find....其实每次操作都开启和关闭session。
一个自动生成的DAO中的save方法:
- public void save(Tenant transientInstance) {
- log.debug("saving Tenant instance");
- try {
- getHibernateTemplate().save(transientInstance);
- log.debug("save successful");
- } catch (RuntimeException re) {
- log.error("save failed", re);
- throw re;
- }
- }
public void save(Tenant transientInstance) { log.debug("saving Tenant instance"); try { getHibernateTemplate().save(transientInstance); log.debug("save successful"); } catch (RuntimeException re) { log.error("save failed", re); throw re; } }
其实内部调用的是HibernateTemplate的save方法,
org.springframework.orm.hibernate3.HibernateTemplate的save方法:
- public Serializable save(final Object entity) throws DataAccessException {
- return (Serializable) execute(new HibernateCallback() {
- public Object doInHibernate(Session session) throws HibernateException {
- checkWriteOperationAllowed(session);
- return session.save(entity);
- }
- }, true);
- }
public Serializable save(final Object entity) throws DataAccessException { return (Serializable) execute(new HibernateCallback() { public Object doInHibernate(Session session) throws HibernateException { checkWriteOperationAllowed(session); return session.save(entity); } }, true); }
HibernateTemplate的save方法中调用的execute方法:
- public Object execute(HibernateCallback action, boolean exposeNativeSession) throws DataAccessException {
- Assert.notNull(action, "Callback object must not be null");
- Session session = getSession();
- boolean existingTransaction = SessionFactoryUtils.isSessionTransactional(session, getSessionFactory());
- if (existingTransaction) {
- logger.debug("Found thread-bound Session for HibernateTemplate");
- }
- FlushMode previousFlushMode = null;
- try {
- previousFlushMode = applyFlushMode(session, existingTransaction);
- enableFilters(session);
- Session sessionToExpose = (exposeNativeSession ? session : createSessionProxy(session));
- Object result = action.doInHibernate(sessionToExpose);
- flushIfNecessary(session, existingTransaction);
- return result;
- }
- catch (HibernateException ex) {
- throw convertHibernateAccessException(ex);
- }
- catch (SQLException ex) {
- throw convertJdbcAccessException(ex);
- }
- catch (RuntimeException ex) {
- <mce:script type="text/javascript" src="http://hi.images.csdn.net/js/blog/tiny_mce/themes/advanced/langs/zh.js" mce_src="http://hi.images.csdn.net/js/blog/tiny_mce/themes/advanced/langs/zh.js"></mce:script><mce:script type="text/javascript" src="http://hi.images.csdn.net/js/blog/tiny_mce/plugins/syntaxhl/langs/zh.js" mce_src="http://hi.images.csdn.net/js/blog/tiny_mce/plugins/syntaxhl/langs/zh.js"></mce:script>// Callback code threw application exception...
- throw ex;
- }
- finally {
- if (existingTransaction) {
- logger.debug("Not closing pre-bound Hibernate Session after HibernateTemplate");
- disableFilters(session);
- if (previousFlushMode != null) {
- session.setFlushMode(previousFlushMode);
- }
- }
- else {
- // Never use deferred close for an explicitly new Session.
- if (isAlwaysUseNewSession()) {
- SessionFactoryUtils.closeSession(session);
- }
- else {
- SessionFactoryUtils.closeSessionOrRegisterDeferredClose(session, getSessionFactory());
- }
- }
- }
- }
public Object execute(HibernateCallback action, boolean exposeNativeSession) throws DataAccessException { Assert.notNull(action, "Callback object must not be null"); Session session = getSession(); boolean existingTransaction = SessionFactoryUtils.isSessionTransactional(session, getSessionFactory()); if (existingTransaction) { logger.debug("Found thread-bound Session for HibernateTemplate"); } FlushMode previousFlushMode = null; try { previousFlushMode = applyFlushMode(session, existingTransaction); enableFilters(session); Session sessionToExpose = (exposeNativeSession ? session : createSessionProxy(session)); Object result = action.doInHibernate(sessionToExpose); flushIfNecessary(session, existingTransaction); return result; } catch (HibernateException ex) { throw convertHibernateAccessException(ex); } catch (SQLException ex) { throw convertJdbcAccessException(ex); } catch (RuntimeException ex) { <mce:script type="text/javascript" src="http://hi.images.csdn.net/js/blog/tiny_mce/themes/advanced/langs/zh.js" mce_src="http://hi.images.csdn.net/js/blog/tiny_mce/themes/advanced/langs/zh.js"></mce:script><mce:script type="text/javascript" src="http://hi.images.csdn.net/js/blog/tiny_mce/plugins/syntaxhl/langs/zh.js" mce_src="http://hi.images.csdn.net/js/blog/tiny_mce/plugins/syntaxhl/langs/zh.js"></mce:script>// Callback code threw application exception... throw ex; } finally { if (existingTransaction) { logger.debug("Not closing pre-bound Hibernate Session after HibernateTemplate"); disableFilters(session); if (previousFlushMode != null) { session.setFlushMode(previousFlushMode); } } else { // Never use deferred close for an explicitly new Session. if (isAlwaysUseNewSession()) { SessionFactoryUtils.closeSession(session); } else { SessionFactoryUtils.closeSessionOrRegisterDeferredClose(session, getSessionFactory()); } } } }
可见在execute方法内有获取session和关闭session的语句,绕了这么一大圈才看到session!
- protected Session getSession() {
- if (isAlwaysUseNewSession()) {
- return SessionFactoryUtils.getNewSession(getSessionFactory(), getEntityInterceptor());
- }
- else if (!isAllowCreate()) {
- return SessionFactoryUtils.getSession(getSessionFactory(), false);
- }
- else {
- return SessionFactoryUtils.getSession(
- getSessionFactory(), getEntityInterceptor(), getJdbcExceptionTranslator());
- }
- }
protected Session getSession() { if (isAlwaysUseNewSession()) { return SessionFactoryUtils.getNewSession(getSessionFactory(), getEntityInterceptor()); } else if (!isAllowCreate()) { return SessionFactoryUtils.getSession(getSessionFactory(), false); } else { return SessionFactoryUtils.getSession( getSessionFactory(), getEntityInterceptor(), getJdbcExceptionTranslator()); } }
注意这里获取session和关闭session的方法,非常的重要!!!!之后在OpenSessionInViewFilter中要提到这里!!!
这里的session关闭并不是session.close()那么简单,这也是在OpenSessionInViewFilter中打开session后,在这里不会被关闭的原因。
可以看到getSession方法中,是利用SessionFactoryUtils.getNewSession来获取session的,继续深入:
- public static Session getSession(SessionFactory sessionFactory, boolean allowCreate)
- throws DataAccessResourceFailureException, IllegalStateException {
- try {
- return doGetSession(sessionFactory, null, null, allowCreate);
- }
- catch (HibernateException ex) {
- throw new DataAccessResourceFailureException("Could not open Hibernate Session", ex);
- }
- }
public static Session getSession(SessionFactory sessionFactory, boolean allowCreate) throws DataAccessResourceFailureException, IllegalStateException { try { return doGetSession(sessionFactory, null, null, allowCreate); } catch (HibernateException ex) { throw new DataAccessResourceFailureException("Could not open Hibernate Session", ex); } }
- private static Session doGetSession(
- SessionFactory sessionFactory, Interceptor entityInterceptor,
- SQLExceptionTranslator jdbcExceptionTranslator, boolean allowCreate)
- throws HibernateException, IllegalStateException {
- Assert.notNull(sessionFactory, "No SessionFactory specified");
- SessionHolder sessionHolder = (SessionHolder) TransactionSynchronizationManager.getResource(sessionFactory);
- if (sessionHolder != null && !sessionHolder.isEmpty()) {
- // pre-bound Hibernate Session
- Session session = null;
- if (TransactionSynchronizationManager.isSynchronizationActive() &&
- sessionHolder.doesNotHoldNonDefaultSession()) {
- // Spring transaction management is active ->
- // register pre-bound Session with it for transactional flushing.
- session = sessionHolder.getValidatedSession();
- if (session != null && !sessionHolder.isSynchronizedWithTransaction()) {
- logger.debug("Registering Spring transaction synchronization for existing Hibernate Session");
- TransactionSynchronizationManager.registerSynchronization(
- new SpringSessionSynchronization(sessionHolder, sessionFactory, jdbcExceptionTranslator, false));
- sessionHolder.setSynchronizedWithTransaction(true);
- // Switch to FlushMode.AUTO, as we have to assume a thread-bound Session
- // with FlushMode.NEVER, which needs to allow flushing within the transaction.
- FlushMode flushMode = session.getFlushMode();
- if (flushMode.lessThan(FlushMode.COMMIT) &&
- !TransactionSynchronizationManager.isCurrentTransactionReadOnly()) {
- session.setFlushMode(FlushMode.AUTO);
- sessionHolder.setPreviousFlushMode(flushMode);
- }
- }
- }
- else {
- // No Spring transaction management active -> try JTA transaction synchronization.
- session = getJtaSynchronizedSession(sessionHolder, sessionFactory, jdbcExceptionTranslator);
- }
- if (session != null) {
- return session;
- }
- }
- logger.debug("Opening Hibernate Session");
- Session session = (entityInterceptor != null ?
- sessionFactory.openSession(entityInterceptor) : sessionFactory.openSession());
- // Use same Session for further Hibernate actions within the transaction.
- // Thread object will get removed by synchronization at transaction completion.
- if (TransactionSynchronizationManager.isSynchronizationActive()) {
- // We're within a Spring-managed transaction, possibly from JtaTransactionManager.
- logger.debug("Registering Spring transaction synchronization for new Hibernate Session");
- SessionHolder holderToUse = sessionHolder;
- if (holderToUse == null) {
- holderToUse = new SessionHolder(session);
- }
- else {
- holderToUse.addSession(session);
- }
- if (TransactionSynchronizationManager.isCurrentTransactionReadOnly()) {
- session.setFlushMode(FlushMode.NEVER);
- }
- TransactionSynchronizationManager.registerSynchronization(
- new SpringSessionSynchronization(holderToUse, sessionFactory, jdbcExceptionTranslator, true));
- holderToUse.setSynchronizedWithTransaction(true);
- if (holderToUse != sessionHolder) {
- TransactionSynchronizationManager.bindResource(sessionFactory, holderToUse);
- }
- }
- else {
- // No Spring transaction management active -> try JTA transaction synchronization.
- registerJtaSynchronization(session, sessionFactory, jdbcExceptionTranslator, sessionHolder);
- }
- // Check whether we are allowed to return the Session.
- if (!allowCreate && !isSessionTransactional(session, sessionFactory)) {
- closeSession(session);
- throw new IllegalStateException("No Hibernate Session bound to thread, " +
- "and configuration does not allow creation of non-transactional one here");
- }
- return session;
- }
private static Session doGetSession( SessionFactory sessionFactory, Interceptor entityInterceptor, SQLExceptionTranslator jdbcExceptionTranslator, boolean allowCreate) throws HibernateException, IllegalStateException { Assert.notNull(sessionFactory, "No SessionFactory specified"); SessionHolder sessionHolder = (SessionHolder) TransactionSynchronizationManager.getResource(sessionFactory); if (sessionHolder != null && !sessionHolder.isEmpty()) { // pre-bound Hibernate Session Session session = null; if (TransactionSynchronizationManager.isSynchronizationActive() && sessionHolder.doesNotHoldNonDefaultSession()) { // Spring transaction management is active -> // register pre-bound Session with it for transactional flushing. session = sessionHolder.getValidatedSession(); if (session != null && !sessionHolder.isSynchronizedWithTransaction()) { logger.debug("Registering Spring transaction synchronization for existing Hibernate Session"); TransactionSynchronizationManager.registerSynchronization( new SpringSessionSynchronization(sessionHolder, sessionFactory, jdbcExceptionTranslator, false)); sessionHolder.setSynchronizedWithTransaction(true); // Switch to FlushMode.AUTO, as we have to assume a thread-bound Session // with FlushMode.NEVER, which needs to allow flushing within the transaction. FlushMode flushMode = session.getFlushMode(); if (flushMode.lessThan(FlushMode.COMMIT) && !TransactionSynchronizationManager.isCurrentTransactionReadOnly()) { session.setFlushMode(FlushMode.AUTO); sessionHolder.setPreviousFlushMode(flushMode); } } } else { // No Spring transaction management active -> try JTA transaction synchronization. session = getJtaSynchronizedSession(sessionHolder, sessionFactory, jdbcExceptionTranslator); } if (session != null) { return session; } } logger.debug("Opening Hibernate Session"); Session session = (entityInterceptor != null ? sessionFactory.openSession(entityInterceptor) : sessionFactory.openSession()); // Use same Session for further Hibernate actions within the transaction. // Thread object will get removed by synchronization at transaction completion. if (TransactionSynchronizationManager.isSynchronizationActive()) { // We're within a Spring-managed transaction, possibly from JtaTransactionManager. logger.debug("Registering Spring transaction synchronization for new Hibernate Session"); SessionHolder holderToUse = sessionHolder; if (holderToUse == null) { holderToUse = new SessionHolder(session); } else { holderToUse.addSession(session); } if (TransactionSynchronizationManager.isCurrentTransactionReadOnly()) { session.setFlushMode(FlushMode.NEVER); } TransactionSynchronizationManager.registerSynchronization( new SpringSessionSynchronization(holderToUse, sessionFactory, jdbcExceptionTranslator, true)); holderToUse.setSynchronizedWithTransaction(true); if (holderToUse != sessionHolder) { TransactionSynchronizationManager.bindResource(sessionFactory, holderToUse); } } else { // No Spring transaction management active -> try JTA transaction synchronization. registerJtaSynchronization(session, sessionFactory, jdbcExceptionTranslator, sessionHolder); } // Check whether we are allowed to return the Session. if (!allowCreate && !isSessionTransactional(session, sessionFactory)) { closeSession(session); throw new IllegalStateException("No Hibernate Session bound to thread, " + "and configuration does not allow creation of non-transactional one here"); } return session; }其实上面一大堆的代码中,我们只需要关注这一句:
SessionHolder sessionHolder = (SessionHolder) TransactionSynchronizationManager.getResource(sessionFactory);
记住TransactionSynchronizationManager类和SessionHolder 类
好了,说了一大堆DAO,下面正式介绍OpenSessionInViewFilter
下面是OpenSessionInViewFilter中主要的方法doFilterInternal:
- protected void doFilterInternal(
- HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
- throws ServletException, IOException {
- SessionFactory sessionFactory = lookupSessionFactory(request);
- boolean participate = false;
- if (isSingleSession()) {
- // single session mode
- if (TransactionSynchronizationManager.hasResource(sessionFactory)) {
- // Do not modify the Session: just set the participate flag.
- participate = true;
- }
- else {
- logger.debug("Opening single Hibernate Session in OpenSessionInViewFilter");
- Session session = getSession(sessionFactory);
- TransactionSynchronizationManager.bindResource(sessionFactory, new SessionHolder(session));
- }
- }
- else {
- // deferred close mode
- if (SessionFactoryUtils.isDeferredCloseActive(sessionFactory)) {
- // Do not modify deferred close: just set the participate flag.
- participate = true;
- }
- else {
- SessionFactoryUtils.initDeferredClose(sessionFactory);
- }
- }
- try {
- filterChain.doFilter(request, response);
- }
- finally {
- if (!participate) {
- if (isSingleSession()) {
- // single session mode
- SessionHolder sessionHolder =
- (SessionHolder) TransactionSynchronizationManager.unbindResource(sessionFactory);
- logger.debug("Closing single Hibernate Session in OpenSessionInViewFilter");
- closeSession(sessionHolder.getSession(), sessionFactory);
- }
- else {
- // deferred close mode
- SessionFactoryUtils.processDeferredClose(sessionFactory);
- }
- }
- }
- }
protected void doFilterInternal( HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException { SessionFactory sessionFactory = lookupSessionFactory(request); boolean participate = false; if (isSingleSession()) { // single session mode if (TransactionSynchronizationManager.hasResource(sessionFactory)) { // Do not modify the Session: just set the participate flag. participate = true; } else { logger.debug("Opening single Hibernate Session in OpenSessionInViewFilter"); Session session = getSession(sessionFactory); TransactionSynchronizationManager.bindResource(sessionFactory, new SessionHolder(session)); } } else { // deferred close mode if (SessionFactoryUtils.isDeferredCloseActive(sessionFactory)) { // Do not modify deferred close: just set the participate flag. participate = true; } else { SessionFactoryUtils.initDeferredClose(sessionFactory); } } try { filterChain.doFilter(request, response); } finally { if (!participate) { if (isSingleSession()) { // single session mode SessionHolder sessionHolder = (SessionHolder) TransactionSynchronizationManager.unbindResource(sessionFactory); logger.debug("Closing single Hibernate Session in OpenSessionInViewFilter"); closeSession(sessionHolder.getSession(), sessionFactory); } else { // deferred close mode SessionFactoryUtils.processDeferredClose(sessionFactory); } } } }
上述代码可简化为:
1. 获取session,打开session
2. filterChain.doFilter(request, response);
3. 关闭session
在2中可能执行了若干的Servlet、JSP、Action等等,最终处理完渲染完页面之后,再进入OpenSessionInViewFilter的3关闭session。
现在只要保证在2中不论是Servlet、JSP还是Action中执行DAO时获取的session都是1中打开的同一个session,并且在DAO关闭session时并不实际关闭,留到OpenSessionInViewFilter的3中再最终关闭,就实现了懒加载了,因为只要是在OpenSessionInViewFilter过滤的范围内,session都处于打开,比如在一个Servlet中查到一个Bean,这时他的关联实体并没有加载,当这个Servlet重定向到一个JSP,在其中得到这个Bean后直接访问之前没加载的那些关联实体,会实时的加载这个关联实体,因为session还未关闭,这便是懒加载了。
下面要证实的是在OpenSessionInViewFilter中打开的session和在DAO中获取的session是相同的,而且在DAO中并不实际关闭该session。
是不是同一个session就要看session是怎么获得的,从上面OpenSessionInViewFilter的doFilterInternal方法中我们看到session是靠其getSession方法中获得,代码如下:
- protected Session getSession(SessionFactory sessionFactory) throws DataAccessResourceFailureException {
- Session session = SessionFactoryUtils.getSession(sessionFactory, true);
- FlushMode flushMode = getFlushMode();
- if (flushMode != null) {
- session.setFlushMode(flushMode);
- }
- return session;
- }
protected Session getSession(SessionFactory sessionFactory) throws DataAccessResourceFailureException { Session session = SessionFactoryUtils.getSession(sessionFactory, true); FlushMode flushMode = getFlushMode(); if (flushMode != null) { session.setFlushMode(flushMode); } return session; }
这里面使用Session session = SessionFactoryUtils.getSession(sessionFactory, true);很眼熟是吗?回头找找DAO获得session的过程(上面加粗的部分),使用的就是这个SessionFactoryUtils类的getSession方法!!!那两个地方得到的是同一个session么?继续向下找,
在SessionFactoryUtils.getSession中,调用了SessionFactoryUtils私有方法doGetSession(),其代码如下:
private static Session doGetSession(
- SessionFactory sessionFactory, Interceptor entityInterceptor,
- SQLExceptionTranslator jdbcExceptionTranslator, boolean allowCreate)
- throws HibernateException, IllegalStateException {
- Assert.notNull(sessionFactory, "No SessionFactory specified");
- SessionHolder sessionHolder = (SessionHolder) TransactionSynchronizationManager.getResource(sessionFactory);
- if (sessionHolder != null && !sessionHolder.isEmpty()) {
- // pre-bound Hibernate Session
- Session session = null;
- if (TransactionSynchronizationManager.isSynchronizationActive() &&
- sessionHolder.doesNotHoldNonDefaultSession()) {
- // Spring transaction management is active ->
- // register pre-bound Session with it for transactional flushing.
- session = sessionHolder.getValidatedSession();
- if (session != null && !sessionHolder.isSynchronizedWithTransaction()) {
- logger.debug("Registering Spring transaction synchronization for existing Hibernate Session");
- TransactionSynchronizationManager.registerSynchronization(
- new SpringSessionSynchronization(sessionHolder, sessionFactory, jdbcExceptionTranslator, false));
- sessionHolder.setSynchronizedWithTransaction(true);
- // Switch to FlushMode.AUTO, as we have to assume a thread-bound Session
- // with FlushMode.NEVER, which needs to allow flushing within the transaction.
- FlushMode flushMode = session.getFlushMode();
- if (flushMode.lessThan(FlushMode.COMMIT) &&
- !TransactionSynchronizationManager.isCurrentTransactionReadOnly()) {
- session.setFlushMode(FlushMode.AUTO);
- sessionHolder.setPreviousFlushMode(flushMode);
- }
- }
- }
- else {
- // No Spring transaction management active -> try JTA transaction synchronization.
- session = getJtaSynchronizedSession(sessionHolder, sessionFactory, jdbcExceptionTranslator);
- }
- if (session != null) {
- return session;
- }
- }
SessionFactory sessionFactory, Interceptor entityInterceptor, SQLExceptionTranslator jdbcExceptionTranslator, boolean allowCreate) throws HibernateException, IllegalStateException { Assert.notNull(sessionFactory, "No SessionFactory specified"); SessionHolder sessionHolder = (SessionHolder) TransactionSynchronizationManager.getResource(sessionFactory); if (sessionHolder != null && !sessionHolder.isEmpty()) { // pre-bound Hibernate Session Session session = null; if (TransactionSynchronizationManager.isSynchronizationActive() && sessionHolder.doesNotHoldNonDefaultSession()) { // Spring transaction management is active -> // register pre-bound Session with it for transactional flushing. session = sessionHolder.getValidatedSession(); if (session != null && !sessionHolder.isSynchronizedWithTransaction()) { logger.debug("Registering Spring transaction synchronization for existing Hibernate Session"); TransactionSynchronizationManager.registerSynchronization( new SpringSessionSynchronization(sessionHolder, sessionFactory, jdbcExceptionTranslator, false)); sessionHolder.setSynchronizedWithTransaction(true); // Switch to FlushMode.AUTO, as we have to assume a thread-bound Session // with FlushMode.NEVER, which needs to allow flushing within the transaction. FlushMode flushMode = session.getFlushMode(); if (flushMode.lessThan(FlushMode.COMMIT) && !TransactionSynchronizationManager.isCurrentTransactionReadOnly()) { session.setFlushMode(FlushMode.AUTO); sessionHolder.setPreviousFlushMode(flushMode); } } } else { // No Spring transaction management active -> try JTA transaction synchronization. session = getJtaSynchronizedSession(sessionHolder, sessionFactory, jdbcExceptionTranslator); } if (session != null) { return session; } }
别的不看,我们仅关注这一句:
SessionHolder sessionHolder = (SessionHolder) TransactionSynchronizationManager.getResource(sessionFactory);
更加眼熟了是吗?看上面加下划线的一行,完全一样是吧,SessionHolder是持有session的类,我们继续看 TransactionSynchronizationManager类,很接近真相了。
- public static Object getResource(Object key)
- {
- Object actualKey = TransactionSynchronizationUtils.unwrapResourceIfNecessary(key);
- Map map = (Map)resources.get();
- if(map == null)
- return null;
- Object value = map.get(actualKey);
- if(value != null && logger.isDebugEnabled())
- logger.debug("Retrieved value [" + value + "] for key [" + actualKey + "] bound to thread [" + Thread.currentThread().getName() + "]");
- return value;
- }
- public static void bindResource(Object key, Object value)
- throws IllegalStateException
- {
- Object actualKey = TransactionSynchronizationUtils.unwrapResourceIfNecessary(key);
- Assert.notNull(value, "Value must not be null");
- Map map = (Map)resources.get();
- if(map == null)
- {
- map = new HashMap();
- resources.set(map);
- }
- if(map.containsKey(actualKey))
- throw new IllegalStateException("Already value [" + map.get(actualKey) + "] for key [" + actualKey + "] bound to thread [" + Thread.currentThread().getName() + "]");
- map.put(actualKey, value);
- if(logger.isDebugEnabled())
- logger.debug("Bound value [" + value + "] for key [" + actualKey + "] to thread [" + Thread.currentThread().getName() + "]");
- }
public static Object getResource(Object key) { Object actualKey = TransactionSynchronizationUtils.unwrapResourceIfNecessary(key); Map map = (Map)resources.get(); if(map == null) return null; Object value = map.get(actualKey); if(value != null && logger.isDebugEnabled()) logger.debug("Retrieved value [" + value + "] for key [" + actualKey + "] bound to thread [" + Thread.currentThread().getName() + "]"); return value; } public static void bindResource(Object key, Object value) throws IllegalStateException { Object actualKey = TransactionSynchronizationUtils.unwrapResourceIfNecessary(key); Assert.notNull(value, "Value must not be null"); Map map = (Map)resources.get(); if(map == null) { map = new HashMap(); resources.set(map); } if(map.containsKey(actualKey)) throw new IllegalStateException("Already value [" + map.get(actualKey) + "] for key [" + actualKey + "] bound to thread [" + Thread.currentThread().getName() + "]"); map.put(actualKey, value); if(logger.isDebugEnabled()) logger.debug("Bound value [" + value + "] for key [" + actualKey + "] to thread [" + Thread.currentThread().getName() + "]"); }看到了吧,上面是 TransactionSynchronizationManager的getResource和bindResource,你也看出来了是吧,内部就是一个map,以传入的sessionFactory作为key查找到session对象,那么两处只要其sessionFactory是同一个,那么通过
TransactionSynchronizationManager获得的session就一定是同一个!!!这么绕,哈哈好晕!
那么sessionFactory在两处是如何取得的呢?
在DAO中,其sessionFactory是在spring配置文件中注入的,如下:
- <bean id="MessageTemplateDAO"
- class="edu.pku.ss.platform.dao.impl.MessageTemplateDAO">
- <property name="sessionFactory">
- <ref bean="platformSessionFactory" />
- </property>
- </bean>
<bean id="MessageTemplateDAO" class="edu.pku.ss.platform.dao.impl.MessageTemplateDAO"> <property name="sessionFactory"> <ref bean="platformSessionFactory" /> </property> </bean>
而中是怎么获得的呢?在中获取的代码如下:
- protected SessionFactory lookupSessionFactory() {
- if (logger.isDebugEnabled()) {
- logger.debug("Using SessionFactory '" + getSessionFactoryBeanName() + "' for OpenSessionInViewFilter");
- }
- WebApplicationContext wac =
- WebApplicationContextUtils.getRequiredWebApplicationContext(getServletContext());
- return (SessionFactory) wac.getBean(getSessionFactoryBeanName(), SessionFactory.class);
- }
protected SessionFactory lookupSessionFactory() { if (logger.isDebugEnabled()) { logger.debug("Using SessionFactory '" + getSessionFactoryBeanName() + "' for OpenSessionInViewFilter"); } WebApplicationContext wac = WebApplicationContextUtils.getRequiredWebApplicationContext(getServletContext()); return (SessionFactory) wac.getBean(getSessionFactoryBeanName(), SessionFactory.class); }WebApplicationContextUtils,getBean()...可见同样是从spring的容器中获得,我的追溯也就到这里,再往下具体spring的bean容器怎么获取对象,貌似不相关了,偷个懒
华丽的分割线,貌似到这里,可以看出,其实在OpenSessionInViewFilter中打开的session和DAO中得到的是同一个session。
那么关闭呢?DAO中的session是如何关闭的呢?这也是我最关心的问题之一
在HibernateTemplate中的execute()方法中(上面有贴完整代码),找到了关闭session的代码,如下:
finally {
- if (existingTransaction) {
- logger.debug("Not closing pre-bound Hibernate Session after HibernateTemplate");
- disableFilters(session);
- if (previousFlushMode != null) {
- session.setFlushMode(previousFlushMode);
- }
- }
- else {
- // Never use deferred close for an explicitly new Session.
- if (isAlwaysUseNewSession()) {
- SessionFactoryUtils.closeSession(session);
- }
- else {
- SessionFactoryUtils.closeSessionOrRegisterDeferredClose(session, getSessionFactory());
- }
- }
- }
if (existingTransaction) { logger.debug("Not closing pre-bound Hibernate Session after HibernateTemplate"); disableFilters(session); if (previousFlushMode != null) { session.setFlushMode(previousFlushMode); } } else { // Never use deferred close for an explicitly new Session. if (isAlwaysUseNewSession()) { SessionFactoryUtils.closeSession(session); } else { SessionFactoryUtils.closeSessionOrRegisterDeferredClose(session, getSessionFactory()); } } }
可见分两种情况,先判断有没有存在事务,如果有,里面的logger中打印的信息为“Not closing pre-bound Hibernate Session after HibernateTemplate”,可见存在事务的时候是不关闭session的那不存在事务呢?又分两种情况,isAlwaysUseNewSession是否始终使用新的session,这里肯定不是啦,DAO中获得的session是OpenSessionInViewFilter中打开的而不是新建的,所以是最后一种情况,即执行:
SessionFactoryUtils.closeSessionOrRegisterDeferredClose(session, getSessionFactory());
从方法名就知道关闭session或延期关闭,那不用问在这个方法里面也做了判断,进去看看:
- static void closeSessionOrRegisterDeferredClose(Session session, SessionFactory sessionFactory) {
- Map holderMap = (Map) deferredCloseHolder.get();
- if (holderMap != null && sessionFactory != null && holderMap.containsKey(sessionFactory)) {
- logger.debug("Registering Hibernate Session for deferred close");
- // Switch Session to FlushMode.NEVER for remaining lifetime.
- session.setFlushMode(FlushMode.NEVER);
- Set sessions = (Set) holderMap.get(sessionFactory);
- sessions.add(session);
- }
- else {
- closeSession(session);
- }
- }
static void closeSessionOrRegisterDeferredClose(Session session, SessionFactory sessionFactory) { Map holderMap = (Map) deferredCloseHolder.get(); if (holderMap != null && sessionFactory != null && holderMap.containsKey(sessionFactory)) { logger.debug("Registering Hibernate Session for deferred close"); // Switch Session to FlushMode.NEVER for remaining lifetime. session.setFlushMode(FlushMode.NEVER); Set sessions = (Set) holderMap.get(sessionFactory); sessions.add(session); } else { closeSession(session); } }
这里面holderMap初始化的地方为:holderMap.put(sessionFactory, CollectionFactory.createLinkedSetIfPossible(4));
又是以sessionFactory为键存入一个Map,那不用问,在这种场景下,holderMap.containsKey(sessionFactory)肯定为真,那么最终会执行session.setFlushMode(FlushMode.NEVER);正如上面的log中的信息所说的Switch Session to FlushMode.NEVER for remaining lifetime. 可见在OpenSessionInViewFilter中打开session时,在DAO中就不会将其关闭了!!!!!!!!!!!!
最后总结一下吧,上面写得这么多,估计谁看了都会晕的....
- 在OpenSessionInViewFilter中以sessionFactory为键向TransactionSynchronizationManager中注册了一个session
- 在DAO中(),按照sessionFactory为键值从TransactionSynchronizationManager获取一个session(当然会是同一个)
- DAO中执行完相应的持久化操作后,在关闭session时,由于在holderMap中找到了sessionFactory这一键值,所以推迟关闭
- 重复前两个步骤,只要是在OpenSessionInViewFilter后的所有JSP、Servlet等等,在使用DAO或DAO的封装时,session始终为同一个并保持打开,即实现懒加载
- 最后在OpenSessionInViewFilter中将session关闭,Flush,完成持久化的写入,最终完成这一次请求响应过程。
嘿嘿上面的总结够简洁了吧
接下来还要回到我在这个项目中配置失败的原因上,我发现虽然我了解了OpenSessionInViewFilter的机制,但是我的页面上还是会抛出no session or session closed,郁闷,后来经过我细致的排查,最终将问题锁定了HTTPSession!!
由于项目中情况复杂,况且也不便透露,我将业务逻辑简化一下,有User和News实体,User保存用户信息,News保存用户发布的新闻,两者为一对多的关系。
当用户登录成功后,将用户的User存入HTTPSession中,在其他页面中,从HTTPSession中获取User,并想显示该用户发布的所有新闻,当然直观的想法是用user.getNews()这个User在逆向工程中自动生成的方法来通过懒加载获取,这种想法本无可厚非,也应该这样,但是问题是这个User是从HTTPSession中取得的!!!这就是问题所在!!!!!!!
因为在用户登录时这个User由于懒加载并没有立即检索其关联的新闻表,然后将User存入HTTPSession中,之后反回用户登陆成功页面,注意此时Hibernate的session已经关闭了!!!!!!!!!尽管User这个对象存在HTTPSession中没有被回收,但是它已经不再是持久化对象了,它的session关闭了,它现在已经是游离对象了!!!!(详见上面4中对象的阐述),游离对象已经是不能再加载其关联的对象了!!!所以才会抛出no session异常,因为早在登录成功时就已经关闭销毁了!
至此,问题解决了,对Hibernate的懒加载的认识有深入一步,希望对同样遇到这类问题的朋友能起到帮助!
相关推荐
OpenSessionInViewFilter是Spring框架中一个非常重要的组件,主要用于解决数据访问...这个文档应该包含了OpenSessionInViewFilter的源码分析、配置示例以及常见问题的解答,对理解该过滤器的功能和工作原理非常有帮助。
OpenSessionInViewFilter个人学习总结
SSH是Java Web开发中的一个流行框架组合,由Struts、Hibernate和Spring三个组件构成。这个框架集成提供了模型-视图-控制器(MVC)架构,数据持久化,以及依赖注入和事务管理等功能,大大简化了企业级应用的开发工作...
Struts2、Spring和Hibernate是Java开发中三个非常重要的框架,它们共同构成了经典的MVC(Model-View-Controller)架构的实现。这个压缩包“struts2.0.8+spring2.0+hibernate3.2”包含了这三个框架的特定版本,这将...
#### 二、懒加载异常现象及原因分析 在使用懒加载技术时,可能会遇到“LazyInitializationException”这类异常。该异常通常发生在试图访问延迟加载的关联对象时,而此时Session已经关闭的情况。例如,在Hibernate中...
在探讨如何通过`OpenSessionInViewFilter`来有效管理Hibernate中的Session生命周期之前,我们需要先理解Session及其生命周期的基本概念。 #### Session与生命周期 在Hibernate框架中,`Session`是执行数据库操作的...
该模式的核心在于通过Spring提供的`OpenSessionInViewFilter`过滤器,在视图渲染过程中保持Hibernate Session的打开状态,从而简化了事务管理,并避免了一些常见的懒加载异常。 #### 一、OpenSessionInViewFilter...
OpenSessionInViewFilter解决Web应用程序的问题
在处理Web应用时,Spring提供了一些关键特性,如`CharacterEncodingFilter`和`OpenSessionInViewFilter`,它们对于解决特定问题至关重要。 首先,让我们深入了解一下`CharacterEncodingFilter`。在Web应用中,字符...
为了解决这个问题,我们可以使用 Spring 提供的一个支持类OpenSessionInViewFilter,这个类可以在发起一个页面请求时打开 Hibernate 的 Session,并保持这个 Session 的生命周期,直到这个请求结束。这样可以确保 ...
### Spring监听器与过滤器详解...- **Spring Web环境下的监听器和过滤器**:在Spring MVC环境中,除了上述提到的OpenSessionInViewFilter和CharacterEncodingFilter,还有多种其他类型的过滤器和监听器可以使用,例如`...
2. **OpenSessionInViewFilter**:通过Web容器的过滤器(filter)来实现。 #### 异常原因 当使用Open Session In View模式时,如果Session的Flush Mode被设置为NEVER,并且尝试执行写操作(如更新或删除),就会触发...
在`web.xml`中配置Spring监听器以初始化Spring容器,并添加`OpenSessionInViewFilter`以解决懒加载问题: ```xml <listener-class>org.springframework.web.context.ContextLoaderListener <filter-name>...
<filter-class>org.springframework.orm.hibernate3.support.OpenSessionInViewFilter ``` - **`OpenSessionInViewFilter`**:开启Hibernate的Session,在视图渲染完成后关闭Session,确保每个HTTP请求都在同一个...
在 OpenSessionInViewFilter 中,需要配置 Hibernate 的 Session 管理,以便实现 Hibernate 的 Session 的打开和关闭。 9. web.xml 配置 在 web.xml 文件中,需要配置 Servlet 监听器、上下文变量、Filter 等,...
Spring MVC Hibernate Demo Hibernate 配置 数据库实体必须设置以下注解 @Entity ... <filter>org.springframework.orm.hibernate4.support.OpenSessionInViewFilter <param>flushMode</param-nam
我们可以通过配置XML文件和注解来实现整合,并使用opensessionInviewfilter来解决会话问题。 Spring JDBC面向接口编程 本节讲解了如何使用Spring JDBC来实现面向接口编程。我们可以通过配置XML文件和注解来实现DAO...
这个案例提供了一个基础的登录功能,同时展示了S2SH集成的各个方面,包括OpenSessionInViewFilter的使用、声明式事务管理以及三层架构的设计。 首先,让我们从Struts2开始。Struts2作为控制层,负责处理HTTP请求,...
Spring框架还提供了一系列的过滤器来处理Web应用中的请求,例如OpenSessionInViewFilter用于解决Hibernate懒加载问题。 - **OpenSessionInViewFilter**:此过滤器在请求处理开始时打开一个Hibernate会话,在请求...
- **Hibernate会话管理过滤器**:OpenSessionInViewFilter确保在每个请求的生命周期内保持一个打开的Hibernate Session,从而实现懒加载: ```xml <filter-name>OpenSessionInViewFilter <filter-class>org....