Search in sources :

Example 1 with EntityManagerHolder

use of org.springframework.orm.jpa.EntityManagerHolder in project spring-framework by spring-projects.

the class OpenEntityManagerInViewFilter method doFilterInternal.

@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
    EntityManagerFactory emf = lookupEntityManagerFactory(request);
    boolean participate = false;
    WebAsyncManager asyncManager = WebAsyncUtils.getAsyncManager(request);
    String key = getAlreadyFilteredAttributeName();
    if (TransactionSynchronizationManager.hasResource(emf)) {
        // Do not modify the EntityManager: just set the participate flag.
        participate = true;
    } else {
        boolean isFirstRequest = !isAsyncDispatch(request);
        if (isFirstRequest || !applyEntityManagerBindingInterceptor(asyncManager, key)) {
            logger.debug("Opening JPA EntityManager in OpenEntityManagerInViewFilter");
            try {
                EntityManager em = createEntityManager(emf);
                EntityManagerHolder emHolder = new EntityManagerHolder(em);
                TransactionSynchronizationManager.bindResource(emf, emHolder);
                AsyncRequestInterceptor interceptor = new AsyncRequestInterceptor(emf, emHolder);
                asyncManager.registerCallableInterceptor(key, interceptor);
                asyncManager.registerDeferredResultInterceptor(key, interceptor);
            } catch (PersistenceException ex) {
                throw new DataAccessResourceFailureException("Could not create JPA EntityManager", ex);
            }
        }
    }
    try {
        filterChain.doFilter(request, response);
    } finally {
        if (!participate) {
            EntityManagerHolder emHolder = (EntityManagerHolder) TransactionSynchronizationManager.unbindResource(emf);
            if (!isAsyncStarted(request)) {
                logger.debug("Closing JPA EntityManager in OpenEntityManagerInViewFilter");
                EntityManagerFactoryUtils.closeEntityManager(emHolder.getEntityManager());
            }
        }
    }
}
Also used : WebAsyncManager(org.springframework.web.context.request.async.WebAsyncManager) EntityManager(javax.persistence.EntityManager) DataAccessResourceFailureException(org.springframework.dao.DataAccessResourceFailureException) EntityManagerFactory(javax.persistence.EntityManagerFactory) PersistenceException(javax.persistence.PersistenceException) EntityManagerHolder(org.springframework.orm.jpa.EntityManagerHolder)

Example 2 with EntityManagerHolder

use of org.springframework.orm.jpa.EntityManagerHolder in project spring-framework by spring-projects.

the class OpenEntityManagerInViewInterceptor method afterCompletion.

@Override
public void afterCompletion(WebRequest request, Exception ex) throws DataAccessException {
    if (!decrementParticipateCount(request)) {
        EntityManagerHolder emHolder = (EntityManagerHolder) TransactionSynchronizationManager.unbindResource(getEntityManagerFactory());
        logger.debug("Closing JPA EntityManager in OpenEntityManagerInViewInterceptor");
        EntityManagerFactoryUtils.closeEntityManager(emHolder.getEntityManager());
    }
}
Also used : EntityManagerHolder(org.springframework.orm.jpa.EntityManagerHolder)

Example 3 with EntityManagerHolder

use of org.springframework.orm.jpa.EntityManagerHolder in project spring-framework by spring-projects.

the class OpenEntityManagerInViewInterceptor method preHandle.

@Override
public void preHandle(WebRequest request) throws DataAccessException {
    String participateAttributeName = getParticipateAttributeName();
    WebAsyncManager asyncManager = WebAsyncUtils.getAsyncManager(request);
    if (asyncManager.hasConcurrentResult()) {
        if (applyCallableInterceptor(asyncManager, participateAttributeName)) {
            return;
        }
    }
    if (TransactionSynchronizationManager.hasResource(getEntityManagerFactory())) {
        // Do not modify the EntityManager: just mark the request accordingly.
        Integer count = (Integer) request.getAttribute(participateAttributeName, WebRequest.SCOPE_REQUEST);
        int newCount = (count != null ? count + 1 : 1);
        request.setAttribute(getParticipateAttributeName(), newCount, WebRequest.SCOPE_REQUEST);
    } else {
        logger.debug("Opening JPA EntityManager in OpenEntityManagerInViewInterceptor");
        try {
            EntityManager em = createEntityManager();
            EntityManagerHolder emHolder = new EntityManagerHolder(em);
            TransactionSynchronizationManager.bindResource(getEntityManagerFactory(), emHolder);
            AsyncRequestInterceptor interceptor = new AsyncRequestInterceptor(getEntityManagerFactory(), emHolder);
            asyncManager.registerCallableInterceptor(participateAttributeName, interceptor);
            asyncManager.registerDeferredResultInterceptor(participateAttributeName, interceptor);
        } catch (PersistenceException ex) {
            throw new DataAccessResourceFailureException("Could not create JPA EntityManager", ex);
        }
    }
}
Also used : WebAsyncManager(org.springframework.web.context.request.async.WebAsyncManager) EntityManager(javax.persistence.EntityManager) DataAccessResourceFailureException(org.springframework.dao.DataAccessResourceFailureException) PersistenceException(javax.persistence.PersistenceException) EntityManagerHolder(org.springframework.orm.jpa.EntityManagerHolder)

Example 4 with EntityManagerHolder

use of org.springframework.orm.jpa.EntityManagerHolder in project spring-framework by spring-projects.

the class PersistenceInjectionTests method testPropertiesForSharedEntityManager2.

@Test
public void testPropertiesForSharedEntityManager2() {
    Properties props = new Properties();
    props.put("foo", "bar");
    EntityManager em = mock(EntityManager.class);
    // only one call made  - the first EM definition wins (in this case the one w/o the properties)
    given(mockEmf.createEntityManager()).willReturn(em);
    given(em.getDelegate()).willReturn(new Object(), 2);
    given(em.isOpen()).willReturn(true);
    PersistenceAnnotationBeanPostProcessor pabpp = new MockPersistenceAnnotationBeanPostProcessor();
    DefaultPrivatePersistenceContextFieldWithProperties transactionalFieldWithProperties = new DefaultPrivatePersistenceContextFieldWithProperties();
    DefaultPrivatePersistenceContextField transactionalField = new DefaultPrivatePersistenceContextField();
    pabpp.postProcessPropertyValues(null, null, transactionalFieldWithProperties, "bean1");
    pabpp.postProcessPropertyValues(null, null, transactionalField, "bean2");
    assertNotNull(transactionalFieldWithProperties.em);
    assertNotNull(transactionalField.em);
    // the EM w/o properties will be created
    assertNotNull(transactionalField.em.getDelegate());
    // bind em to the thread now since it's created
    try {
        TransactionSynchronizationManager.bindResource(mockEmf, new EntityManagerHolder(em));
        assertNotNull(transactionalFieldWithProperties.em.getDelegate());
        verify(em).close();
    } finally {
        TransactionSynchronizationManager.unbindResource(mockEmf);
    }
}
Also used : EntityManager(javax.persistence.EntityManager) Properties(java.util.Properties) EntityManagerHolder(org.springframework.orm.jpa.EntityManagerHolder) Test(org.junit.Test)

Example 5 with EntityManagerHolder

use of org.springframework.orm.jpa.EntityManagerHolder in project spring-framework by spring-projects.

the class PersistenceInjectionTests method testPropertiesForSharedEntityManager1.

/**
	 * Binds an EMF to the thread and tests if EM with different properties
	 * generate new EMs or not.
	 */
@Test
public void testPropertiesForSharedEntityManager1() {
    Properties props = new Properties();
    props.put("foo", "bar");
    EntityManager em = mock(EntityManager.class);
    // only one call made  - the first EM definition wins (in this case the one w/ the properties)
    given(mockEmf.createEntityManager(props)).willReturn(em);
    given(em.getDelegate()).willReturn(new Object());
    given(em.isOpen()).willReturn(true);
    PersistenceAnnotationBeanPostProcessor pabpp = new MockPersistenceAnnotationBeanPostProcessor();
    DefaultPrivatePersistenceContextFieldWithProperties transactionalFieldWithProperties = new DefaultPrivatePersistenceContextFieldWithProperties();
    DefaultPrivatePersistenceContextField transactionalField = new DefaultPrivatePersistenceContextField();
    pabpp.postProcessPropertyValues(null, null, transactionalFieldWithProperties, "bean1");
    pabpp.postProcessPropertyValues(null, null, transactionalField, "bean2");
    assertNotNull(transactionalFieldWithProperties.em);
    assertNotNull(transactionalField.em);
    // the EM w/ properties will be created
    assertNotNull(transactionalFieldWithProperties.em.getDelegate());
    // bind em to the thread now since it's created
    try {
        TransactionSynchronizationManager.bindResource(mockEmf, new EntityManagerHolder(em));
        assertNotNull(transactionalField.em.getDelegate());
        verify(em).close();
    } finally {
        TransactionSynchronizationManager.unbindResource(mockEmf);
    }
}
Also used : EntityManager(javax.persistence.EntityManager) Properties(java.util.Properties) EntityManagerHolder(org.springframework.orm.jpa.EntityManagerHolder) Test(org.junit.Test)

Aggregations

EntityManagerHolder (org.springframework.orm.jpa.EntityManagerHolder)9 EntityManager (javax.persistence.EntityManager)7 EntityManagerFactory (javax.persistence.EntityManagerFactory)3 Test (org.junit.Test)3 Properties (java.util.Properties)2 PersistenceException (javax.persistence.PersistenceException)2 DataAccessResourceFailureException (org.springframework.dao.DataAccessResourceFailureException)2 WebAsyncManager (org.springframework.web.context.request.async.WebAsyncManager)2 Around (org.aspectj.lang.annotation.Around)1 EntityManagerProxy (org.springframework.orm.jpa.EntityManagerProxy)1