1 16 17 package org.springframework.orm.jpa; 18 19 import javax.persistence.EntityManager; 20 21 import org.aopalliance.intercept.MethodInterceptor; 22 import org.aopalliance.intercept.MethodInvocation; 23 24 import org.springframework.transaction.support.TransactionSynchronizationManager; 25 26 66 public class JpaInterceptor extends JpaAccessor implements MethodInterceptor { 67 68 private boolean exceptionConversionEnabled = true; 69 70 71 78 public void setExceptionConversionEnabled(boolean exceptionConversionEnabled) { 79 this.exceptionConversionEnabled = exceptionConversionEnabled; 80 } 81 82 83 public Object invoke(MethodInvocation methodInvocation) throws Throwable { 84 EntityManager em = getTransactionalEntityManager(); 87 boolean isNewEm = false; 88 if (em == null) { 89 logger.debug("Creating new EntityManager for JpaInterceptor invocation"); 90 em = createEntityManager(); 91 isNewEm = true; 92 TransactionSynchronizationManager.bindResource(getEntityManagerFactory(), new EntityManagerHolder(em)); 93 } 94 95 try { 96 Object retVal = methodInvocation.proceed(); 97 flushIfNecessary(em, !isNewEm); 98 return retVal; 99 } 100 catch (RuntimeException rawException) { 101 if (this.exceptionConversionEnabled) { 102 throw translateIfNecessary(rawException); 104 } 105 else { 106 throw rawException; 108 } 109 } 110 finally { 111 if (isNewEm) { 112 TransactionSynchronizationManager.unbindResource(getEntityManagerFactory()); 113 logger.debug("Closing new EntityManager after JpaInterceptor invocation"); 114 em.close(); 115 } 116 } 117 } 118 119 } 120 | Popular Tags |