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