Search in sources :

Example 11 with EntityManagerFactory

use of javax.persistence.EntityManagerFactory 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 12 with EntityManagerFactory

use of javax.persistence.EntityManagerFactory in project spring-framework by spring-projects.

the class HibernateJpaSessionFactoryBean method getObject.

@Override
public SessionFactory getObject() {
    EntityManagerFactory emf = getEntityManagerFactory();
    Assert.state(emf != null, "EntityManagerFactory must not be null");
    try {
        Method getSessionFactory = emf.getClass().getMethod("getSessionFactory");
        return (SessionFactory) ReflectionUtils.invokeMethod(getSessionFactory, emf);
    } catch (NoSuchMethodException ex) {
        throw new IllegalStateException("No compatible Hibernate EntityManagerFactory found: " + ex);
    }
}
Also used : SessionFactory(org.hibernate.SessionFactory) EntityManagerFactory(javax.persistence.EntityManagerFactory) Method(java.lang.reflect.Method)

Example 13 with EntityManagerFactory

use of javax.persistence.EntityManagerFactory in project spring-framework by spring-projects.

the class LocalContainerEntityManagerFactoryBeanTests method testApplicationManagedEntityManagerWithJtaTransaction.

@Test
public void testApplicationManagedEntityManagerWithJtaTransaction() throws Exception {
    Object testEntity = new Object();
    // This one's for the tx (shared)
    EntityManager sharedEm = mock(EntityManager.class);
    given(sharedEm.getTransaction()).willReturn(new NoOpEntityTransaction());
    // This is the application-specific one
    EntityManager mockEm = mock(EntityManager.class);
    given(mockEmf.createEntityManager()).willReturn(sharedEm, mockEm);
    LocalContainerEntityManagerFactoryBean cefb = parseValidPersistenceUnit();
    MutablePersistenceUnitInfo pui = ((MutablePersistenceUnitInfo) cefb.getPersistenceUnitInfo());
    pui.setTransactionType(PersistenceUnitTransactionType.JTA);
    JpaTransactionManager jpatm = new JpaTransactionManager();
    jpatm.setEntityManagerFactory(cefb.getObject());
    TransactionStatus txStatus = jpatm.getTransaction(new DefaultTransactionAttribute());
    EntityManagerFactory emf = cefb.getObject();
    assertSame("EntityManagerFactory reference must be cached after init", emf, cefb.getObject());
    assertNotSame("EMF must be proxied", mockEmf, emf);
    EntityManager em = emf.createEntityManager();
    em.joinTransaction();
    assertFalse(em.contains(testEntity));
    jpatm.commit(txStatus);
    cefb.destroy();
    verify(mockEm).joinTransaction();
    verify(mockEm).contains(testEntity);
    verify(mockEmf).close();
}
Also used : EntityManager(javax.persistence.EntityManager) DefaultTransactionAttribute(org.springframework.transaction.interceptor.DefaultTransactionAttribute) EntityManagerFactory(javax.persistence.EntityManagerFactory) TransactionStatus(org.springframework.transaction.TransactionStatus) MutablePersistenceUnitInfo(org.springframework.orm.jpa.persistenceunit.MutablePersistenceUnitInfo) Test(org.junit.Test)

Example 14 with EntityManagerFactory

use of javax.persistence.EntityManagerFactory in project spring-framework by spring-projects.

the class LocalContainerEntityManagerFactoryBeanTests method testEntityManagerFactoryIsProxied.

@Test
public void testEntityManagerFactoryIsProxied() throws Exception {
    LocalContainerEntityManagerFactoryBean cefb = parseValidPersistenceUnit();
    EntityManagerFactory emf = cefb.getObject();
    assertSame("EntityManagerFactory reference must be cached after init", emf, cefb.getObject());
    assertNotSame("EMF must be proxied", mockEmf, emf);
    assertTrue(emf.equals(emf));
    DefaultListableBeanFactory bf = new DefaultListableBeanFactory();
    bf.setSerializationId("emf-bf");
    bf.registerSingleton("emf", cefb);
    cefb.setBeanFactory(bf);
    cefb.setBeanName("emf");
    assertNotNull(SerializationTestUtils.serializeAndDeserialize(emf));
}
Also used : EntityManagerFactory(javax.persistence.EntityManagerFactory) DefaultListableBeanFactory(org.springframework.beans.factory.support.DefaultListableBeanFactory) Test(org.junit.Test)

Example 15 with EntityManagerFactory

use of javax.persistence.EntityManagerFactory in project spring-framework by spring-projects.

the class OpenEntityManagerInViewTests method testOpenEntityManagerInViewFilterAsyncScenario.

@Test
public void testOpenEntityManagerInViewFilterAsyncScenario() throws Exception {
    given(manager.isOpen()).willReturn(true);
    final EntityManagerFactory factory2 = mock(EntityManagerFactory.class);
    final EntityManager manager2 = mock(EntityManager.class);
    given(factory2.createEntityManager()).willReturn(manager2);
    given(manager2.isOpen()).willReturn(true);
    MockServletContext sc = new MockServletContext();
    StaticWebApplicationContext wac = new StaticWebApplicationContext();
    wac.setServletContext(sc);
    wac.getDefaultListableBeanFactory().registerSingleton("entityManagerFactory", factory);
    wac.getDefaultListableBeanFactory().registerSingleton("myEntityManagerFactory", factory2);
    wac.refresh();
    sc.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, wac);
    MockFilterConfig filterConfig = new MockFilterConfig(wac.getServletContext(), "filter");
    MockFilterConfig filterConfig2 = new MockFilterConfig(wac.getServletContext(), "filter2");
    filterConfig2.addInitParameter("entityManagerFactoryBeanName", "myEntityManagerFactory");
    final OpenEntityManagerInViewFilter filter = new OpenEntityManagerInViewFilter();
    filter.init(filterConfig);
    final OpenEntityManagerInViewFilter filter2 = new OpenEntityManagerInViewFilter();
    filter2.init(filterConfig2);
    final AtomicInteger count = new AtomicInteger(0);
    final FilterChain filterChain = new FilterChain() {

        @Override
        public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse) {
            assertTrue(TransactionSynchronizationManager.hasResource(factory));
            servletRequest.setAttribute("invoked", Boolean.TRUE);
            count.incrementAndGet();
        }
    };
    final AtomicInteger count2 = new AtomicInteger(0);
    final FilterChain filterChain2 = new FilterChain() {

        @Override
        public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse) throws IOException, ServletException {
            assertTrue(TransactionSynchronizationManager.hasResource(factory2));
            filter.doFilter(servletRequest, servletResponse, filterChain);
            count2.incrementAndGet();
        }
    };
    FilterChain filterChain3 = new PassThroughFilterChain(filter2, filterChain2);
    AsyncWebRequest asyncWebRequest = mock(AsyncWebRequest.class);
    given(asyncWebRequest.isAsyncStarted()).willReturn(true);
    WebAsyncManager asyncManager = WebAsyncUtils.getAsyncManager(this.request);
    asyncManager.setTaskExecutor(new SyncTaskExecutor());
    asyncManager.setAsyncWebRequest(asyncWebRequest);
    asyncManager.startCallableProcessing(new Callable<String>() {

        @Override
        public String call() throws Exception {
            return "anything";
        }
    });
    assertFalse(TransactionSynchronizationManager.hasResource(factory));
    assertFalse(TransactionSynchronizationManager.hasResource(factory2));
    filter2.doFilter(this.request, this.response, filterChain3);
    assertFalse(TransactionSynchronizationManager.hasResource(factory));
    assertFalse(TransactionSynchronizationManager.hasResource(factory2));
    assertEquals(1, count.get());
    assertEquals(1, count2.get());
    assertNotNull(request.getAttribute("invoked"));
    verify(asyncWebRequest, times(2)).addCompletionHandler(any(Runnable.class));
    verify(asyncWebRequest).addTimeoutHandler(any(Runnable.class));
    verify(asyncWebRequest, times(2)).addCompletionHandler(any(Runnable.class));
    verify(asyncWebRequest).startAsync();
    // Async dispatch after concurrent handling produces result ...
    reset(asyncWebRequest);
    given(asyncWebRequest.isAsyncStarted()).willReturn(false);
    assertFalse(TransactionSynchronizationManager.hasResource(factory));
    assertFalse(TransactionSynchronizationManager.hasResource(factory2));
    filter.doFilter(this.request, this.response, filterChain3);
    assertFalse(TransactionSynchronizationManager.hasResource(factory));
    assertFalse(TransactionSynchronizationManager.hasResource(factory2));
    assertEquals(2, count.get());
    assertEquals(2, count2.get());
    verify(this.manager).close();
    verify(manager2).close();
    wac.close();
}
Also used : WebAsyncManager(org.springframework.web.context.request.async.WebAsyncManager) ServletRequest(javax.servlet.ServletRequest) MockHttpServletRequest(org.springframework.mock.web.test.MockHttpServletRequest) MockHttpServletResponse(org.springframework.mock.web.test.MockHttpServletResponse) ServletResponse(javax.servlet.ServletResponse) FilterChain(javax.servlet.FilterChain) PassThroughFilterChain(org.springframework.mock.web.test.PassThroughFilterChain) StaticWebApplicationContext(org.springframework.web.context.support.StaticWebApplicationContext) AsyncWebRequest(org.springframework.web.context.request.async.AsyncWebRequest) StandardServletAsyncWebRequest(org.springframework.web.context.request.async.StandardServletAsyncWebRequest) MockServletContext(org.springframework.mock.web.test.MockServletContext) ServletException(javax.servlet.ServletException) IOException(java.io.IOException) MockFilterConfig(org.springframework.mock.web.test.MockFilterConfig) EntityManager(javax.persistence.EntityManager) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) EntityManagerFactory(javax.persistence.EntityManagerFactory) PassThroughFilterChain(org.springframework.mock.web.test.PassThroughFilterChain) Test(org.junit.Test)

Aggregations

EntityManagerFactory (javax.persistence.EntityManagerFactory)165 Test (org.junit.Test)72 EntityManager (javax.persistence.EntityManager)55 HashMap (java.util.HashMap)21 EJBException (javax.ejb.EJBException)19 AssertionFailedError (junit.framework.AssertionFailedError)17 TestFailureException (org.apache.openejb.test.TestFailureException)17 JMSException (javax.jms.JMSException)15 Map (java.util.Map)14 RemoteException (java.rmi.RemoteException)11 InitialContext (javax.naming.InitialContext)11 EntityTransaction (javax.persistence.EntityTransaction)10 PersistenceUnitDescriptorAdapter (org.hibernate.jpa.test.PersistenceUnitDescriptorAdapter)10 NamingException (javax.naming.NamingException)8 PersistenceProvider (javax.persistence.spi.PersistenceProvider)7 BeanContext (org.apache.openejb.BeanContext)7 Item (org.hibernate.jpa.test.Item)7 Method (java.lang.reflect.Method)6 URL (java.net.URL)6 ArrayList (java.util.ArrayList)6