Search in sources :

Example 16 with EntityManagerFactory

use of jakarta.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(jakarta.persistence.EntityManager) DataAccessResourceFailureException(org.springframework.dao.DataAccessResourceFailureException) EntityManagerFactory(jakarta.persistence.EntityManagerFactory) PersistenceException(jakarta.persistence.PersistenceException) EntityManagerHolder(org.springframework.orm.jpa.EntityManagerHolder)

Example 17 with EntityManagerFactory

use of jakarta.persistence.EntityManagerFactory in project jOOQ by jOOQ.

the class Setup method run.

// This class sets up an EntityManager and configures the jOOQ DSLContext
// ----------------------------------------------------------------------
static void run(BiConsumer<EntityManager, DSLContext> consumer) throws Exception {
    Connection connection = null;
    EntityManagerFactory emf = null;
    EntityManager em = null;
    try {
        // Bootstrapping JDBC:
        Class.forName("org.h2.Driver");
        connection = new LoggingConnection(DriverManager.getConnection("jdbc:h2:mem:jooq-jpa-example", "sa", ""));
        final Connection c = connection;
        // Creating an in-memory H2 database from our entities
        MetadataSources metadata = new MetadataSources(new StandardServiceRegistryBuilder().applySetting("hibernate.dialect", "org.hibernate.dialect.H2Dialect").applySetting("javax.persistence.schema-generation-connection", connection).applySetting("javax.persistence.create-database-schemas", true).applySetting(AvailableSettings.CONNECTION_PROVIDER, new ConnectionProvider() {

            @SuppressWarnings("rawtypes")
            @Override
            public boolean isUnwrappableAs(Class unwrapType) {
                return false;
            }

            @Override
            public <T> T unwrap(Class<T> unwrapType) {
                return null;
            }

            @Override
            public Connection getConnection() {
                return c;
            }

            @Override
            public void closeConnection(Connection conn) throws SQLException {
            }

            @Override
            public boolean supportsAggressiveRelease() {
                return true;
            }
        }).build());
        metadata.addAnnotatedClass(Actor.class);
        metadata.addAnnotatedClass(Film.class);
        metadata.addAnnotatedClass(Language.class);
        SchemaExport export = new SchemaExport();
        export.create(EnumSet.of(TargetType.DATABASE), metadata.buildMetadata());
        Map<Object, Object> props = new HashMap<>();
        DataSource ds = new SingleConnectionDataSource(connection);
        props.put("hibernate.connection.datasource", ds);
        props.put("hibernate.archive.autodetection", "");
        emf = new HibernatePersistenceProvider().createContainerEntityManagerFactory(pui(ds), props);
        em = emf.createEntityManager();
        final EntityManager e = em;
        // Run some Hibernate / jOOQ logic inside of a transaction
        em.getTransaction().begin();
        data(em);
        consumer.accept(em, new DefaultConfiguration().set(connection).set(onStart(ctx -> e.flush())).dsl());
        em.getTransaction().commit();
    } finally {
        if (em != null)
            em.close();
        if (emf != null)
            emf.close();
        if (connection != null)
            connection.close();
    }
}
Also used : LoggingConnection(org.jooq.tools.jdbc.LoggingConnection) Language(org.jooq.example.jpa.entity.Language) Arrays(java.util.Arrays) Connection(java.sql.Connection) URL(java.net.URL) AvailableSettings(org.hibernate.cfg.AvailableSettings) PersistenceUnitTransactionType(jakarta.persistence.spi.PersistenceUnitTransactionType) HashMap(java.util.HashMap) StandardServiceRegistryBuilder(org.hibernate.boot.registry.StandardServiceRegistryBuilder) Film(org.jooq.example.jpa.entity.Film) ValidationMode(jakarta.persistence.ValidationMode) ExecuteListener.onStart(org.jooq.ExecuteListener.onStart) Title(org.jooq.example.jpa.embeddables.Title) SQLException(java.sql.SQLException) Map(java.util.Map) BiConsumer(java.util.function.BiConsumer) DataSource(javax.sql.DataSource) DSLContext(org.jooq.DSLContext) ClassTransformer(jakarta.persistence.spi.ClassTransformer) SchemaExport(org.hibernate.tool.hbm2ddl.SchemaExport) EnumSet(java.util.EnumSet) SharedCacheMode(jakarta.persistence.SharedCacheMode) TargetType(org.hibernate.tool.schema.TargetType) LoggingConnection(org.jooq.tools.jdbc.LoggingConnection) Properties(java.util.Properties) DefaultConfiguration(org.jooq.impl.DefaultConfiguration) IOException(java.io.IOException) EntityManagerFactory(jakarta.persistence.EntityManagerFactory) PersistenceUnitInfo(jakarta.persistence.spi.PersistenceUnitInfo) MetadataSources(org.hibernate.boot.MetadataSources) UncheckedIOException(java.io.UncheckedIOException) List(java.util.List) HibernatePersistenceProvider(org.hibernate.jpa.HibernatePersistenceProvider) Year(java.time.Year) EntityManager(jakarta.persistence.EntityManager) Actor(org.jooq.example.jpa.entity.Actor) ConnectionProvider(org.hibernate.engine.jdbc.connections.spi.ConnectionProvider) Collections(java.util.Collections) DriverManager(java.sql.DriverManager) SingleConnectionDataSource(org.jooq.tools.jdbc.SingleConnectionDataSource) SingleConnectionDataSource(org.jooq.tools.jdbc.SingleConnectionDataSource) StandardServiceRegistryBuilder(org.hibernate.boot.registry.StandardServiceRegistryBuilder) SQLException(java.sql.SQLException) HashMap(java.util.HashMap) Connection(java.sql.Connection) LoggingConnection(org.jooq.tools.jdbc.LoggingConnection) MetadataSources(org.hibernate.boot.MetadataSources) HibernatePersistenceProvider(org.hibernate.jpa.HibernatePersistenceProvider) DefaultConfiguration(org.jooq.impl.DefaultConfiguration) ConnectionProvider(org.hibernate.engine.jdbc.connections.spi.ConnectionProvider) DataSource(javax.sql.DataSource) SingleConnectionDataSource(org.jooq.tools.jdbc.SingleConnectionDataSource) EntityManager(jakarta.persistence.EntityManager) EntityManagerFactory(jakarta.persistence.EntityManagerFactory) SchemaExport(org.hibernate.tool.hbm2ddl.SchemaExport)

Example 18 with EntityManagerFactory

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

the class PersistenceContextTransactionTests method setup.

@BeforeEach
public void setup() {
    factory = mock(EntityManagerFactory.class);
    manager = mock(EntityManager.class);
    tx = mock(EntityTransaction.class);
    JpaTransactionManager tm = new JpaTransactionManager(factory);
    tt = new TransactionTemplate(tm);
    given(factory.createEntityManager()).willReturn(manager);
    given(manager.getTransaction()).willReturn(tx);
    given(manager.isOpen()).willReturn(true);
    bean = new EntityManagerHoldingBean();
    @SuppressWarnings("serial") PersistenceAnnotationBeanPostProcessor pabpp = new PersistenceAnnotationBeanPostProcessor() {

        @Override
        protected EntityManagerFactory findEntityManagerFactory(@Nullable String unitName, String requestingBeanName) {
            return factory;
        }
    };
    pabpp.postProcessProperties(null, bean, "bean");
    assertThat(TransactionSynchronizationManager.getResourceMap().isEmpty()).isTrue();
    assertThat(TransactionSynchronizationManager.isSynchronizationActive()).isFalse();
}
Also used : EntityTransaction(jakarta.persistence.EntityTransaction) EntityManager(jakarta.persistence.EntityManager) EntityManagerFactory(jakarta.persistence.EntityManagerFactory) JpaTransactionManager(org.springframework.orm.jpa.JpaTransactionManager) TransactionTemplate(org.springframework.transaction.support.TransactionTemplate) Nullable(org.springframework.lang.Nullable) BeforeEach(org.junit.jupiter.api.BeforeEach)

Example 19 with EntityManagerFactory

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

the class PersistenceInjectionTests method testPrivatePersistenceContextField.

@Test
public void testPrivatePersistenceContextField() throws Exception {
    mockEmf = mock(EntityManagerFactory.class, withSettings().serializable());
    GenericApplicationContext gac = new GenericApplicationContext();
    gac.getDefaultListableBeanFactory().registerSingleton("entityManagerFactory", mockEmf);
    gac.registerBeanDefinition("annotationProcessor", new RootBeanDefinition(PersistenceAnnotationBeanPostProcessor.class));
    gac.registerBeanDefinition(DefaultPrivatePersistenceContextField.class.getName(), new RootBeanDefinition(DefaultPrivatePersistenceContextField.class));
    gac.registerBeanDefinition(FactoryBeanWithPersistenceContextField.class.getName(), new RootBeanDefinition(FactoryBeanWithPersistenceContextField.class));
    gac.refresh();
    DefaultPrivatePersistenceContextField bean = (DefaultPrivatePersistenceContextField) gac.getBean(DefaultPrivatePersistenceContextField.class.getName());
    FactoryBeanWithPersistenceContextField bean2 = (FactoryBeanWithPersistenceContextField) gac.getBean("&" + FactoryBeanWithPersistenceContextField.class.getName());
    assertThat(bean.em).isNotNull();
    assertThat(bean2.em).isNotNull();
    assertThat(SerializationTestUtils.serializeAndDeserialize(bean.em)).isNotNull();
    assertThat(SerializationTestUtils.serializeAndDeserialize(bean2.em)).isNotNull();
}
Also used : GenericApplicationContext(org.springframework.context.support.GenericApplicationContext) EntityManagerFactory(jakarta.persistence.EntityManagerFactory) RootBeanDefinition(org.springframework.beans.factory.support.RootBeanDefinition) Test(org.junit.jupiter.api.Test)

Example 20 with EntityManagerFactory

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

the class OpenEntityManagerInViewTests method testOpenEntityManagerInViewFilter.

@Test
public void testOpenEntityManagerInViewFilter() 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);
    MockHttpServletRequest request = new MockHttpServletRequest(sc);
    MockHttpServletResponse response = new MockHttpServletResponse();
    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 FilterChain filterChain = (servletRequest, servletResponse) -> {
        assertThat(TransactionSynchronizationManager.hasResource(factory)).isTrue();
        servletRequest.setAttribute("invoked", Boolean.TRUE);
    };
    final FilterChain filterChain2 = (servletRequest, servletResponse) -> {
        assertThat(TransactionSynchronizationManager.hasResource(factory2)).isTrue();
        filter.doFilter(servletRequest, servletResponse, filterChain);
    };
    FilterChain filterChain3 = new PassThroughFilterChain(filter2, filterChain2);
    assertThat(TransactionSynchronizationManager.hasResource(factory)).isFalse();
    assertThat(TransactionSynchronizationManager.hasResource(factory2)).isFalse();
    filter2.doFilter(request, response, filterChain3);
    assertThat(TransactionSynchronizationManager.hasResource(factory)).isFalse();
    assertThat(TransactionSynchronizationManager.hasResource(factory2)).isFalse();
    assertThat(request.getAttribute("invoked")).isNotNull();
    verify(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) EntityManager(jakarta.persistence.EntityManager) MockHttpServletRequest(org.springframework.web.testfixture.servlet.MockHttpServletRequest) EntityManagerFactory(jakarta.persistence.EntityManagerFactory) FilterChain(jakarta.servlet.FilterChain) PassThroughFilterChain(org.springframework.web.testfixture.servlet.PassThroughFilterChain) PassThroughFilterChain(org.springframework.web.testfixture.servlet.PassThroughFilterChain) StaticWebApplicationContext(org.springframework.web.context.support.StaticWebApplicationContext) MockServletContext(org.springframework.web.testfixture.servlet.MockServletContext) MockHttpServletResponse(org.springframework.web.testfixture.servlet.MockHttpServletResponse) MockFilterConfig(org.springframework.web.testfixture.servlet.MockFilterConfig) Test(org.junit.jupiter.api.Test)

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