1 16 17 package org.springframework.orm.hibernate3; 18 19 import org.aopalliance.intercept.MethodInterceptor; 20 import org.aopalliance.intercept.MethodInvocation; 21 import org.hibernate.FlushMode; 22 import org.hibernate.HibernateException; 23 import org.hibernate.Session; 24 25 import org.springframework.transaction.support.TransactionSynchronizationManager; 26 27 72 public class HibernateInterceptor extends HibernateAccessor implements MethodInterceptor { 73 74 private boolean exceptionConversionEnabled = true; 75 76 77 84 public void setExceptionConversionEnabled(boolean exceptionConversionEnabled) { 85 this.exceptionConversionEnabled = exceptionConversionEnabled; 86 } 87 88 89 public Object invoke(MethodInvocation methodInvocation) throws Throwable { 90 Session session = getSession(); 91 boolean existingTransaction = SessionFactoryUtils.isSessionTransactional(session, getSessionFactory()); 92 93 if (existingTransaction) { 94 logger.debug("Found thread-bound Session for HibernateInterceptor"); 95 } 96 else { 97 TransactionSynchronizationManager.bindResource(getSessionFactory(), new SessionHolder(session)); 98 } 99 100 FlushMode previousFlushMode = null; 101 try { 102 previousFlushMode = applyFlushMode(session, existingTransaction); 103 enableFilters(session); 104 Object retVal = methodInvocation.proceed(); 105 flushIfNecessary(session, existingTransaction); 106 return retVal; 107 } 108 catch (HibernateException ex) { 109 if (this.exceptionConversionEnabled) { 110 throw convertHibernateAccessException(ex); 111 } 112 else { 113 throw ex; 114 } 115 } 116 finally { 117 if (existingTransaction) { 118 logger.debug("Not closing pre-bound Hibernate Session after HibernateInterceptor"); 119 disableFilters(session); 120 if (previousFlushMode != null) { 121 session.setFlushMode(previousFlushMode); 122 } 123 } 124 else { 125 TransactionSynchronizationManager.unbindResource(getSessionFactory()); 126 SessionFactoryUtils.closeSessionOrRegisterDeferredClose(session, getSessionFactory()); 127 } 128 } 129 } 130 131 135 protected Session getSession() { 136 return SessionFactoryUtils.getSession( 137 getSessionFactory(), getEntityInterceptor(), getJdbcExceptionTranslator()); 138 } 139 140 } 141 | Popular Tags |