1 16 17 package org.springframework.orm.jpa.support; 18 19 import javax.persistence.EntityManager; 20 import javax.persistence.PersistenceException; 21 22 import org.springframework.dao.DataAccessException; 23 import org.springframework.dao.DataAccessResourceFailureException; 24 import org.springframework.orm.jpa.EntityManagerFactoryAccessor; 25 import org.springframework.orm.jpa.EntityManagerHolder; 26 import org.springframework.transaction.support.TransactionSynchronizationManager; 27 import org.springframework.ui.ModelMap; 28 import org.springframework.web.context.request.WebRequest; 29 import org.springframework.web.context.request.WebRequestInterceptor; 30 31 57 public class OpenEntityManagerInViewInterceptor extends EntityManagerFactoryAccessor implements WebRequestInterceptor { 58 59 65 public static final String PARTICIPATE_SUFFIX = ".PARTICIPATE"; 66 67 68 public void preHandle(WebRequest request) throws DataAccessException { 69 if (TransactionSynchronizationManager.hasResource(getEntityManagerFactory())) { 70 String participateAttributeName = getParticipateAttributeName(); 72 Integer count = (Integer ) request.getAttribute(participateAttributeName, WebRequest.SCOPE_REQUEST); 73 int newCount = (count != null) ? count.intValue() + 1 : 1; 74 request.setAttribute(getParticipateAttributeName(), new Integer (newCount), WebRequest.SCOPE_REQUEST); 75 } 76 else { 77 logger.debug("Opening JPA EntityManager in OpenEntityManagerInViewInterceptor"); 78 try { 79 EntityManager em = createEntityManager(); 80 TransactionSynchronizationManager.bindResource(getEntityManagerFactory(), new EntityManagerHolder(em)); 81 } 82 catch (PersistenceException ex) { 83 throw new DataAccessResourceFailureException("Could not create JPA EntityManager", ex); 84 } 85 } 86 } 87 88 public void postHandle(WebRequest request, ModelMap model) { 89 } 90 91 public void afterCompletion(WebRequest request, Exception ex) throws DataAccessException { 92 String participateAttributeName = getParticipateAttributeName(); 93 Integer count = (Integer ) request.getAttribute(participateAttributeName, WebRequest.SCOPE_REQUEST); 94 if (count != null) { 95 if (count.intValue() > 1) { 97 request.setAttribute(participateAttributeName, new Integer (count.intValue() - 1), WebRequest.SCOPE_REQUEST); 98 } 99 else { 100 request.removeAttribute(participateAttributeName, WebRequest.SCOPE_REQUEST); 101 } 102 } 103 else { 104 EntityManagerHolder emHolder = (EntityManagerHolder) 105 TransactionSynchronizationManager.unbindResource(getEntityManagerFactory()); 106 logger.debug("Closing JPA EntityManager in OpenEntityManagerInViewInterceptor"); 107 emHolder.getEntityManager().close(); 108 } 109 } 110 111 117 protected String getParticipateAttributeName() { 118 return getEntityManagerFactory().toString() + PARTICIPATE_SUFFIX; 119 } 120 121 } 122 | Popular Tags |