Search in sources :

Example 11 with EntityManagerFactory

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

the class SharedEntityManagerCreatorTests method deferredStoredProcedureQueryWithIndexedParameters.

@Test
public void deferredStoredProcedureQueryWithIndexedParameters() {
    EntityManagerFactory emf = mock(EntityManagerFactory.class);
    EntityManager targetEm = mock(EntityManager.class);
    StoredProcedureQuery query = mock(StoredProcedureQuery.class);
    given(emf.createEntityManager()).willReturn(targetEm);
    given(targetEm.createStoredProcedureQuery("x")).willReturn(query);
    willReturn("y").given(query).getOutputParameterValue(0);
    willReturn("z").given(query).getOutputParameterValue(2);
    given(targetEm.isOpen()).willReturn(true);
    EntityManager em = SharedEntityManagerCreator.createSharedEntityManager(emf);
    StoredProcedureQuery spq = em.createStoredProcedureQuery("x");
    spq.registerStoredProcedureParameter(0, String.class, ParameterMode.OUT);
    spq.registerStoredProcedureParameter(1, Number.class, ParameterMode.IN);
    spq.registerStoredProcedureParameter(2, Object.class, ParameterMode.INOUT);
    spq.execute();
    assertThat(spq.getOutputParameterValue(0)).isEqualTo("y");
    assertThatIllegalArgumentException().isThrownBy(() -> spq.getOutputParameterValue(1));
    assertThat(spq.getOutputParameterValue(2)).isEqualTo("z");
    verify(query).registerStoredProcedureParameter(0, String.class, ParameterMode.OUT);
    verify(query).registerStoredProcedureParameter(1, Number.class, ParameterMode.IN);
    verify(query).registerStoredProcedureParameter(2, Object.class, ParameterMode.INOUT);
    verify(query).execute();
    verify(targetEm).close();
    verifyNoMoreInteractions(query);
    verifyNoMoreInteractions(targetEm);
}
Also used : EntityManager(jakarta.persistence.EntityManager) StoredProcedureQuery(jakarta.persistence.StoredProcedureQuery) EntityManagerFactory(jakarta.persistence.EntityManagerFactory) Test(org.junit.jupiter.api.Test)

Example 12 with EntityManagerFactory

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

the class SharedEntityManagerCreatorTests method deferredQueryWithSingleResult.

@Test
public void deferredQueryWithSingleResult() {
    EntityManagerFactory emf = mock(EntityManagerFactory.class);
    EntityManager targetEm = mock(EntityManager.class);
    Query query = mock(Query.class);
    given(emf.createEntityManager()).willReturn(targetEm);
    given(targetEm.createQuery("x")).willReturn(query);
    given(targetEm.isOpen()).willReturn(true);
    EntityManager em = SharedEntityManagerCreator.createSharedEntityManager(emf);
    em.createQuery("x").getSingleResult();
    verify(query).getSingleResult();
    verify(targetEm).close();
}
Also used : EntityManager(jakarta.persistence.EntityManager) StoredProcedureQuery(jakarta.persistence.StoredProcedureQuery) Query(jakarta.persistence.Query) EntityManagerFactory(jakarta.persistence.EntityManagerFactory) Test(org.junit.jupiter.api.Test)

Example 13 with EntityManagerFactory

use of jakarta.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();
    assertThat(cefb.getObject()).as("EntityManagerFactory reference must be cached after init").isSameAs(emf);
    assertThat(emf).as("EMF must be proxied").isNotSameAs(mockEmf);
    assertThat(emf.equals(emf)).isTrue();
    DefaultListableBeanFactory bf = new DefaultListableBeanFactory();
    bf.setSerializationId("emf-bf");
    bf.registerSingleton("emf", cefb);
    cefb.setBeanFactory(bf);
    cefb.setBeanName("emf");
    assertThat(SerializationTestUtils.serializeAndDeserialize(emf)).isNotNull();
}
Also used : EntityManagerFactory(jakarta.persistence.EntityManagerFactory) DefaultListableBeanFactory(org.springframework.beans.factory.support.DefaultListableBeanFactory) Test(org.junit.jupiter.api.Test)

Example 14 with EntityManagerFactory

use of jakarta.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();
    assertThat(cefb.getObject()).as("EntityManagerFactory reference must be cached after init").isSameAs(emf);
    assertThat(emf).as("EMF must be proxied").isNotSameAs(mockEmf);
    EntityManager em = emf.createEntityManager();
    em.joinTransaction();
    assertThat(em.contains(testEntity)).isFalse();
    jpatm.commit(txStatus);
    cefb.destroy();
    verify(mockEm).joinTransaction();
    verify(mockEm).contains(testEntity);
    verify(mockEmf).close();
}
Also used : EntityManager(jakarta.persistence.EntityManager) DefaultTransactionAttribute(org.springframework.transaction.interceptor.DefaultTransactionAttribute) EntityManagerFactory(jakarta.persistence.EntityManagerFactory) TransactionStatus(org.springframework.transaction.TransactionStatus) MutablePersistenceUnitInfo(org.springframework.orm.jpa.persistenceunit.MutablePersistenceUnitInfo) Test(org.junit.jupiter.api.Test)

Example 15 with EntityManagerFactory

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

the class OpenEntityManagerInViewInterceptor method preHandle.

@Override
public void preHandle(WebRequest request) throws DataAccessException {
    String key = getParticipateAttributeName();
    WebAsyncManager asyncManager = WebAsyncUtils.getAsyncManager(request);
    if (asyncManager.hasConcurrentResult() && applyEntityManagerBindingInterceptor(asyncManager, key)) {
        return;
    }
    EntityManagerFactory emf = obtainEntityManagerFactory();
    if (TransactionSynchronizationManager.hasResource(emf)) {
        // Do not modify the EntityManager: just mark the request accordingly.
        Integer count = (Integer) request.getAttribute(key, 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(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);
        }
    }
}
Also used : WebAsyncManager(org.springframework.web.context.request.async.WebAsyncManager) EntityManager(jakarta.persistence.EntityManager) DataAccessResourceFailureException(org.springframework.dao.DataAccessResourceFailureException) EntityManagerFactory(jakarta.persistence.EntityManagerFactory) PersistenceException(jakarta.persistence.PersistenceException) EntityManagerHolder(org.springframework.orm.jpa.EntityManagerHolder)

Aggregations

EntityManagerFactory (jakarta.persistence.EntityManagerFactory)34 Test (org.junit.jupiter.api.Test)27 EntityManager (jakarta.persistence.EntityManager)25 StoredProcedureQuery (jakarta.persistence.StoredProcedureQuery)6 TransactionRequiredException (jakarta.persistence.TransactionRequiredException)6 Query (jakarta.persistence.Query)4 WebAsyncManager (org.springframework.web.context.request.async.WebAsyncManager)4 EntityTransaction (jakarta.persistence.EntityTransaction)3 RootBeanDefinition (org.springframework.beans.factory.support.RootBeanDefinition)3 GenericApplicationContext (org.springframework.context.support.GenericApplicationContext)3 EntityManagerHolder (org.springframework.orm.jpa.EntityManagerHolder)3 PersistenceException (jakarta.persistence.PersistenceException)2 AsyncEvent (jakarta.servlet.AsyncEvent)2 AsyncListener (jakarta.servlet.AsyncListener)2 FilterChain (jakarta.servlet.FilterChain)2 Callable (java.util.concurrent.Callable)2 CountDownLatch (java.util.concurrent.CountDownLatch)2 TimeUnit (java.util.concurrent.TimeUnit)2 AtomicInteger (java.util.concurrent.atomic.AtomicInteger)2 Assertions.assertThat (org.assertj.core.api.Assertions.assertThat)2