Search in sources :

Example 1 with EntityManager

use of jakarta.persistence.EntityManager 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();
    final FilterChain filterChain = (servletRequest, servletResponse) -> {
        assertThat(TransactionSynchronizationManager.hasResource(factory)).isTrue();
        servletRequest.setAttribute("invoked", Boolean.TRUE);
        count.incrementAndGet();
    };
    final AtomicInteger count2 = new AtomicInteger();
    final FilterChain filterChain2 = (servletRequest, servletResponse) -> {
        assertThat(TransactionSynchronizationManager.hasResource(factory2)).isTrue();
        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(this.taskExecutor);
    asyncManager.setAsyncWebRequest(asyncWebRequest);
    asyncManager.startCallableProcessing((Callable<String>) () -> "anything");
    this.taskExecutor.await();
    assertThat(asyncManager.getConcurrentResult()).as("Concurrent result ").isEqualTo("anything");
    assertThat(TransactionSynchronizationManager.hasResource(factory)).isFalse();
    assertThat(TransactionSynchronizationManager.hasResource(factory2)).isFalse();
    filter2.doFilter(this.request, this.response, filterChain3);
    assertThat(TransactionSynchronizationManager.hasResource(factory)).isFalse();
    assertThat(TransactionSynchronizationManager.hasResource(factory2)).isFalse();
    assertThat(count.get()).isEqualTo(1);
    assertThat(count2.get()).isEqualTo(1);
    assertThat(request.getAttribute("invoked")).isNotNull();
    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);
    assertThat(TransactionSynchronizationManager.hasResource(factory)).isFalse();
    assertThat(TransactionSynchronizationManager.hasResource(factory2)).isFalse();
    filter.doFilter(this.request, this.response, filterChain3);
    assertThat(TransactionSynchronizationManager.hasResource(factory)).isFalse();
    assertThat(TransactionSynchronizationManager.hasResource(factory2)).isFalse();
    assertThat(count.get()).isEqualTo(2);
    assertThat(count2.get()).isEqualTo(2);
    verify(this.manager).close();
    verify(manager2).close();
    wac.close();
}
Also used : ArgumentMatchers.any(org.mockito.ArgumentMatchers.any) BeforeEach(org.junit.jupiter.api.BeforeEach) Assertions.assertThat(org.assertj.core.api.Assertions.assertThat) AsyncWebRequest(org.springframework.web.context.request.async.AsyncWebRequest) StaticWebApplicationContext(org.springframework.web.context.support.StaticWebApplicationContext) Callable(java.util.concurrent.Callable) WebAsyncManager(org.springframework.web.context.request.async.WebAsyncManager) TransactionSynchronizationManager(org.springframework.transaction.support.TransactionSynchronizationManager) ServletWebRequest(org.springframework.web.context.request.ServletWebRequest) MockHttpServletResponse(org.springframework.web.testfixture.servlet.MockHttpServletResponse) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) BDDMockito.given(org.mockito.BDDMockito.given) SimpleAsyncTaskExecutor(org.springframework.core.task.SimpleAsyncTaskExecutor) AsyncEvent(jakarta.servlet.AsyncEvent) StandardServletAsyncWebRequest(org.springframework.web.context.request.async.StandardServletAsyncWebRequest) WebAsyncUtils(org.springframework.web.context.request.async.WebAsyncUtils) MockHttpServletRequest(org.springframework.web.testfixture.servlet.MockHttpServletRequest) FilterChain(jakarta.servlet.FilterChain) WebApplicationContext(org.springframework.web.context.WebApplicationContext) MockFilterConfig(org.springframework.web.testfixture.servlet.MockFilterConfig) Mockito.times(org.mockito.Mockito.times) EntityManagerFactory(jakarta.persistence.EntityManagerFactory) Mockito.verify(org.mockito.Mockito.verify) TimeUnit(java.util.concurrent.TimeUnit) Test(org.junit.jupiter.api.Test) CountDownLatch(java.util.concurrent.CountDownLatch) AfterEach(org.junit.jupiter.api.AfterEach) AsyncListener(jakarta.servlet.AsyncListener) EntityManager(jakarta.persistence.EntityManager) MockAsyncContext(org.springframework.web.testfixture.servlet.MockAsyncContext) PassThroughFilterChain(org.springframework.web.testfixture.servlet.PassThroughFilterChain) Mockito.reset(org.mockito.Mockito.reset) MockServletContext(org.springframework.web.testfixture.servlet.MockServletContext) Mockito.mock(org.mockito.Mockito.mock) WebAsyncManager(org.springframework.web.context.request.async.WebAsyncManager) FilterChain(jakarta.servlet.FilterChain) PassThroughFilterChain(org.springframework.web.testfixture.servlet.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.web.testfixture.servlet.MockServletContext) MockFilterConfig(org.springframework.web.testfixture.servlet.MockFilterConfig) EntityManager(jakarta.persistence.EntityManager) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) EntityManagerFactory(jakarta.persistence.EntityManagerFactory) PassThroughFilterChain(org.springframework.web.testfixture.servlet.PassThroughFilterChain) Test(org.junit.jupiter.api.Test)

Example 2 with EntityManager

use of jakarta.persistence.EntityManager in project spring-framework by spring-projects.

the class PersistenceInjectionTests method testPublicExtendedPersistenceContextSetterWithEntityManagerInfoAndSerialization.

@Test
@SuppressWarnings({ "unchecked", "rawtypes" })
public void testPublicExtendedPersistenceContextSetterWithEntityManagerInfoAndSerialization() throws Exception {
    EntityManager mockEm = mock(EntityManager.class, withSettings().serializable());
    given(mockEm.isOpen()).willReturn(true);
    EntityManagerFactoryWithInfo mockEmf = mock(EntityManagerFactoryWithInfo.class);
    given(mockEmf.getJpaDialect()).willReturn(new DefaultJpaDialect());
    given(mockEmf.getEntityManagerInterface()).willReturn((Class) EntityManager.class);
    given(mockEmf.getBeanClassLoader()).willReturn(getClass().getClassLoader());
    given(mockEmf.createNativeEntityManager(null)).willReturn(mockEm);
    GenericApplicationContext gac = new GenericApplicationContext();
    gac.getDefaultListableBeanFactory().registerSingleton("entityManagerFactory", mockEmf);
    gac.registerBeanDefinition("annotationProcessor", new RootBeanDefinition(PersistenceAnnotationBeanPostProcessor.class));
    gac.registerBeanDefinition(DefaultPublicPersistenceContextSetter.class.getName(), new RootBeanDefinition(DefaultPublicPersistenceContextSetter.class));
    gac.refresh();
    DefaultPublicPersistenceContextSetter bean = (DefaultPublicPersistenceContextSetter) gac.getBean(DefaultPublicPersistenceContextSetter.class.getName());
    assertThat(bean.em).isNotNull();
    assertThat(SerializationTestUtils.serializeAndDeserialize(bean.em)).isNotNull();
}
Also used : EntityManager(jakarta.persistence.EntityManager) GenericApplicationContext(org.springframework.context.support.GenericApplicationContext) RootBeanDefinition(org.springframework.beans.factory.support.RootBeanDefinition) DefaultJpaDialect(org.springframework.orm.jpa.DefaultJpaDialect) Test(org.junit.jupiter.api.Test)

Example 3 with EntityManager

use of jakarta.persistence.EntityManager in project spring-framework by spring-projects.

the class PersistenceInjectionTests method testPublicExtendedPersistenceContextSetterWithOverriding.

@Test
public void testPublicExtendedPersistenceContextSetterWithOverriding() {
    EntityManager mockEm2 = mock(EntityManager.class);
    GenericApplicationContext gac = new GenericApplicationContext();
    gac.getDefaultListableBeanFactory().registerSingleton("entityManagerFactory", mockEmf);
    gac.registerBeanDefinition("annotationProcessor", new RootBeanDefinition(PersistenceAnnotationBeanPostProcessor.class));
    RootBeanDefinition bd = new RootBeanDefinition(DefaultPublicPersistenceContextSetter.class);
    bd.getPropertyValues().add("entityManager", mockEm2);
    gac.registerBeanDefinition(DefaultPublicPersistenceContextSetter.class.getName(), bd);
    gac.refresh();
    DefaultPublicPersistenceContextSetter bean = (DefaultPublicPersistenceContextSetter) gac.getBean(DefaultPublicPersistenceContextSetter.class.getName());
    assertThat(bean.em).isSameAs(mockEm2);
}
Also used : EntityManager(jakarta.persistence.EntityManager) GenericApplicationContext(org.springframework.context.support.GenericApplicationContext) RootBeanDefinition(org.springframework.beans.factory.support.RootBeanDefinition) Test(org.junit.jupiter.api.Test)

Example 4 with EntityManager

use of jakarta.persistence.EntityManager in project spring-framework by spring-projects.

the class PersistenceInjectionTests method testNoPropertiesPassedIn.

@Test
public void testNoPropertiesPassedIn() {
    EntityManager mockEm = mock(EntityManager.class);
    given(mockEmf.createEntityManager()).willReturn(mockEm);
    PersistenceAnnotationBeanPostProcessor pabpp = new MockPersistenceAnnotationBeanPostProcessor();
    DefaultPrivatePersistenceContextFieldExtended dppcf = new DefaultPrivatePersistenceContextFieldExtended();
    pabpp.postProcessProperties(null, dppcf, "bean");
    assertThat(dppcf.em).isNotNull();
}
Also used : EntityManager(jakarta.persistence.EntityManager) Test(org.junit.jupiter.api.Test)

Example 5 with EntityManager

use of jakarta.persistence.EntityManager in project spring-framework by spring-projects.

the class SharedEntityManagerCreatorTests method transactionRequiredExceptionOnMerge.

@Test
public void transactionRequiredExceptionOnMerge() {
    EntityManagerFactory emf = mock(EntityManagerFactory.class);
    EntityManager em = SharedEntityManagerCreator.createSharedEntityManager(emf);
    assertThatExceptionOfType(TransactionRequiredException.class).isThrownBy(() -> em.merge(new Object()));
}
Also used : EntityManager(jakarta.persistence.EntityManager) TransactionRequiredException(jakarta.persistence.TransactionRequiredException) EntityManagerFactory(jakarta.persistence.EntityManagerFactory) Test(org.junit.jupiter.api.Test)

Aggregations

EntityManager (jakarta.persistence.EntityManager)55 Test (org.junit.jupiter.api.Test)52 EntityManagerFactory (jakarta.persistence.EntityManagerFactory)25 Query (jakarta.persistence.Query)9 RootBeanDefinition (org.springframework.beans.factory.support.RootBeanDefinition)9 TransactionRequiredException (jakarta.persistence.TransactionRequiredException)7 Person (org.springframework.orm.jpa.domain.Person)7 StoredProcedureQuery (jakarta.persistence.StoredProcedureQuery)6 Properties (java.util.Properties)5 GenericApplicationContext (org.springframework.context.support.GenericApplicationContext)5 EntityManagerHolder (org.springframework.orm.jpa.EntityManagerHolder)5 EntityTransaction (jakarta.persistence.EntityTransaction)4 HashMap (java.util.HashMap)4 DefaultListableBeanFactory (org.springframework.beans.factory.support.DefaultListableBeanFactory)4 ExpectedLookupTemplate (org.springframework.context.testfixture.jndi.ExpectedLookupTemplate)4 TransactionStatus (org.springframework.transaction.TransactionStatus)4 NoResultException (jakarta.persistence.NoResultException)3 Assertions.assertThat (org.assertj.core.api.Assertions.assertThat)3 AfterEach (org.junit.jupiter.api.AfterEach)3 BeforeEach (org.junit.jupiter.api.BeforeEach)3