Search in sources :

Example 6 with ConnectionPolicy

use of org.eclipse.persistence.sessions.server.ConnectionPolicy in project eclipselink by eclipse-ee4j.

the class TestBasicPersistence method testNonpooledConnectionWithErrorOnReleaseConnection.

@Test
public void testNonpooledConnectionWithErrorOnReleaseConnection() throws Exception {
    System.out.println("********************");
    System.out.println("*BEGIN testNonpooledConnectionWithErrorOnReleaseConnection()");
    if (emf == null)
        return;
    final EntityManagerFactoryImpl emfi = emf.unwrap(EntityManagerFactoryImpl.class);
    Assert.assertNotNull(emfi);
    // Create an em with a unpooled connection policy, idea taken from EntityManagerJUnitTestSuite.testNonPooledConnection()
    final ServerSession ss = emfi.getServerSession();
    // cache the original driver name and connection string.
    try {
        setupDriverWrapper(ss);
        DriverWrapper.repairAll();
        // Clone the connection policy and set the pool name to null to emulate using non-pooled connections
        final ConnectionPolicy connectionPolicy = (ConnectionPolicy) ss.getDefaultConnectionPolicy().clone();
        connectionPolicy.setLogin(ss.getLogin());
        connectionPolicy.setPoolName(null);
        final Map<String, Object> properties = new HashMap<>();
        properties.put(EntityManagerProperties.CONNECTION_POLICY, connectionPolicy);
        // Validate against initial non-pooled connection count
        final int initialNonPooledConnections = ss.getNumberOfNonPooledConnectionsUsed();
        final int maxNonPooledConnections = ss.getMaxNumberOfNonPooledConnections();
        System.out.println("initialNonPooledConnections = " + initialNonPooledConnections);
        System.out.println("maxNonPooledConnections = " + maxNonPooledConnections);
        if (maxNonPooledConnections != -1 && initialNonPooledConnections >= maxNonPooledConnections) {
            Assert.fail("initialNonPooledConnections >= maxNonPooledConnections, other tests may be leaking.");
        }
        EntityManager em = emf.createEntityManager(properties);
        EntityTransaction et = em.getTransaction();
        try {
            et.begin();
            Person p = new Person();
            Dog d = new Dog("Bingo");
            p.setDog(d);
            d.setOwner(p);
            em.persist(p);
            em.persist(d);
            em.persist(new XmlFish());
            final int nonPooledConnectionsBeforeFlush = ss.getNumberOfNonPooledConnectionsUsed();
            System.out.println("nonPooledConnectionsBeforeFlush = " + nonPooledConnectionsBeforeFlush);
            em.flush();
            final int nonPooledConnectionsAfterFlush = ss.getNumberOfNonPooledConnectionsUsed();
            System.out.println("nonPooledConnectionsAfterFlush = " + nonPooledConnectionsAfterFlush);
            Assert.assertEquals("nonPooledConnectionsBeforeFlush + 1 == nonPooledConnectionsAfterFlush", nonPooledConnectionsBeforeFlush + 1, nonPooledConnectionsAfterFlush);
            // The non-pooled Connection would be released after the commit.
            DriverWrapper.breakOldConnections();
            try {
                et.commit();
                Assert.fail("No RollbackException was thrown.");
            } catch (RollbackException re) {
            // Expected
            } finally {
                DriverWrapper.repairAll();
            }
            int nonPooledConnectionsAfterCommit = ss.getNumberOfNonPooledConnectionsUsed();
            System.out.println("nonPooledConnectionsAfterCommit = " + nonPooledConnectionsAfterCommit);
            Assert.assertTrue("initialNonPooledConnections >= nonPooledConnectionsAfterCommit", initialNonPooledConnections >= nonPooledConnectionsAfterCommit);
        } finally {
            DriverWrapper.repairAll();
            if (et.isActive()) {
                et.rollback();
            }
            em.close();
        }
    } finally {
        DriverWrapper.repairAll();
        System.out.println("*END testNonpooledConnectionWithErrorOnReleaseConnection()");
    }
}
Also used : EntityTransaction(jakarta.persistence.EntityTransaction) ServerSession(org.eclipse.persistence.sessions.server.ServerSession) HashMap(java.util.HashMap) EntityManagerFactoryImpl(org.eclipse.persistence.internal.jpa.EntityManagerFactoryImpl) RollbackException(jakarta.persistence.RollbackException) EntityManager(jakarta.persistence.EntityManager) XmlFish(org.eclipse.persistence.jpa.test.basic.model.XmlFish) ConnectionPolicy(org.eclipse.persistence.sessions.server.ConnectionPolicy) Person(org.eclipse.persistence.jpa.test.basic.model.Person) Dog(org.eclipse.persistence.jpa.test.basic.model.Dog) Test(org.junit.Test)

Example 7 with ConnectionPolicy

use of org.eclipse.persistence.sessions.server.ConnectionPolicy in project eclipselink by eclipse-ee4j.

the class TestBasicPersistence method testNonpooledConnection.

/*
     * Verify that the number of non pooled connections used is accounted for accurately in regular non-error scenario usage.
     */
@Test
public void testNonpooledConnection() throws Exception {
    System.out.println("********************");
    System.out.println("*BEGIN testNonpooledConnection()");
    if (emf == null)
        return;
    final EntityManagerFactoryImpl emfi = emf.unwrap(EntityManagerFactoryImpl.class);
    Assert.assertNotNull(emfi);
    // Create an em with a unpooled connection policy, idea taken from EntityManagerJUnitTestSuite.testNonPooledConnection()
    final ServerSession ss = emfi.getServerSession();
    // Clone the connection policy and set the pool name to null to emulate using non-pooled connections
    final ConnectionPolicy connectionPolicy = (ConnectionPolicy) ss.getDefaultConnectionPolicy().clone();
    connectionPolicy.setLogin(ss.getLogin());
    connectionPolicy.setPoolName(null);
    final Map<String, Object> properties = new HashMap<>();
    properties.put(EntityManagerProperties.CONNECTION_POLICY, connectionPolicy);
    final int initialNonPooledConnections = ss.getNumberOfNonPooledConnectionsUsed();
    final int maxNonPooledConnections = ss.getMaxNumberOfNonPooledConnections();
    System.out.println("initialNonPooledConnections = " + initialNonPooledConnections);
    System.out.println("maxNonPooledConnections = " + maxNonPooledConnections);
    if (maxNonPooledConnections != -1 && initialNonPooledConnections >= maxNonPooledConnections) {
        Assert.fail("initialNonPooledConnections >= maxNonPooledConnections, other tests may be leaking.");
    }
    EntityManager em = emf.createEntityManager(properties);
    EntityTransaction et = em.getTransaction();
    try {
        et.begin();
        Person p = new Person();
        Dog d = new Dog("Bingo");
        p.setDog(d);
        d.setOwner(p);
        em.persist(p);
        em.persist(d);
        em.persist(new XmlFish());
        em.flush();
        int nonPooledConnectionsAfterFlush = ss.getNumberOfNonPooledConnectionsUsed();
        System.out.println("nonPooledConnectionsAfterFlush = " + nonPooledConnectionsAfterFlush);
        Assert.assertTrue("Test problem: connection should be not pooled", em.unwrap(UnitOfWork.class).getParent().getAccessor().getPool() == null);
        Assert.assertEquals(initialNonPooledConnections + 1, nonPooledConnectionsAfterFlush);
        et.commit();
        em.clear();
        int nonPooledConnectionsAfterCommit = ss.getNumberOfNonPooledConnectionsUsed();
        System.out.println("nonPooledConnectionsAfterCommit = " + nonPooledConnectionsAfterCommit);
        Assert.assertEquals(initialNonPooledConnections, nonPooledConnectionsAfterCommit);
        Dog foundDog = em.find(Dog.class, d.getId());
        foundDog.getOwner();
        Assert.assertTrue(_sql.size() > 0);
        int nonPooledConnectionsAfterFind = ss.getNumberOfNonPooledConnectionsUsed();
        System.out.println("nonPooledConnectionsAfterFind = " + nonPooledConnectionsAfterFind);
        Assert.assertEquals(initialNonPooledConnections, nonPooledConnectionsAfterFind);
    } finally {
        if (et.isActive()) {
            et.rollback();
        }
        em.close();
        System.out.println("*END testNonpooledConnection()");
    }
}
Also used : EntityTransaction(jakarta.persistence.EntityTransaction) UnitOfWork(org.eclipse.persistence.sessions.UnitOfWork) ServerSession(org.eclipse.persistence.sessions.server.ServerSession) HashMap(java.util.HashMap) EntityManagerFactoryImpl(org.eclipse.persistence.internal.jpa.EntityManagerFactoryImpl) EntityManager(jakarta.persistence.EntityManager) XmlFish(org.eclipse.persistence.jpa.test.basic.model.XmlFish) ConnectionPolicy(org.eclipse.persistence.sessions.server.ConnectionPolicy) Person(org.eclipse.persistence.jpa.test.basic.model.Person) Dog(org.eclipse.persistence.jpa.test.basic.model.Dog) Test(org.junit.Test)

Example 8 with ConnectionPolicy

use of org.eclipse.persistence.sessions.server.ConnectionPolicy in project eclipselink by eclipse-ee4j.

the class EntityManagerJUnitTestSuite method internalTestConnectionPolicy.

public void internalTestConnectionPolicy(boolean useSetProperty) {
    // setup
    String errorMsg = "";
    // number of composite members
    int n = 3;
    Map mapOfProperties = new HashMap();
    for (int i = 1; i <= n; i++) {
        String prefix = "em_" + i + "_";
        Map properties = new HashMap();
        properties.put(EntityManagerProperties.JDBC_USER, prefix + "user");
        properties.put(EntityManagerProperties.JDBC_PASSWORD, prefix + "password");
        properties.put(EntityManagerProperties.JTA_DATASOURCE, prefix + "jta_datasource");
        properties.put(EntityManagerProperties.NON_JTA_DATASOURCE, prefix + "nonjta_datasource");
        properties.put(EntityManagerProperties.EXCLUSIVE_CONNECTION_MODE, ExclusiveConnectionMode.Always);
        mapOfProperties.put(getCompositeMemberPuName(i), properties);
    }
    HashMap properties = null;
    if (!useSetProperty) {
        properties = new HashMap(1);
        properties.put(EntityManagerProperties.COMPOSITE_UNIT_PROPERTIES, mapOfProperties);
    }
    // test
    EntityManager em = null;
    boolean isInTransaction = false;
    try {
        // assume that if JTA is used on server then EntityManager is always injected.
        boolean isEmInjected = isOnServer() && getDatabaseSession().hasExternalTransactionController();
        if (isEmInjected) {
            em = createEntityManager();
            // In server jta case need a transaction - otherwise the wrapped EntityManagerImpl is not kept.
            beginTransaction(em);
            isInTransaction = true;
            ((EntityManagerImpl) em.getDelegate()).setProperties(properties);
        } else {
            EntityManagerFactory emFactory = getEntityManagerFactory();
            em = emFactory.createEntityManager(properties);
        }
        if (useSetProperty) {
            em.setProperty(EntityManagerProperties.COMPOSITE_UNIT_PROPERTIES, mapOfProperties);
        }
        for (int i = 1; i <= n; i++) {
            // verify
            SessionBroker clientSessionBroker;
            if (isOnServer()) {
                clientSessionBroker = (SessionBroker) ((EntityManagerImpl) em.getDelegate()).getActivePersistenceContext(null).getParent();
            } else {
                clientSessionBroker = (SessionBroker) ((EntityManagerImpl) em).getActivePersistenceContext(null).getParent();
            }
            ClientSession clientSession = (ClientSession) clientSessionBroker.getSessionForName(getCompositeMemberPuName(i));
            if (!clientSession.isExclusiveIsolatedClientSession()) {
                errorMsg += "ExclusiveIsolatedClientSession was expected\n";
            }
            ConnectionPolicy policy = clientSession.getConnectionPolicy();
            if (policy.isPooled()) {
                errorMsg += "NOT pooled policy was expected\n";
            }
            String user = (String) policy.getLogin().getProperty("user");
            String prefix = "em_" + i + "_";
            if (!user.equals(prefix + "user")) {
                errorMsg += prefix + "user was expected\n";
            }
            String password = (String) policy.getLogin().getProperty("password");
            if (!password.equals(prefix + "password")) {
                errorMsg += prefix + "password was expected\n";
            }
            if (!(((DatasourceLogin) policy.getLogin()).getConnector() instanceof JNDIConnector)) {
                errorMsg += "JNDIConnector was expected\n";
            } else {
                JNDIConnector jndiConnector = (JNDIConnector) ((DatasourceLogin) policy.getLogin()).getConnector();
                String dataSourceName = jndiConnector.getName();
                if (dataSourceName == null) {
                    errorMsg += "NON null dataSourceName was expected\n";
                } else {
                    if (clientSession.getParent().getLogin().shouldUseExternalTransactionController()) {
                        if (dataSourceName.equals(prefix + "nonjta_datasource")) {
                            errorMsg += prefix + "jta_datasource was expected\n";
                        }
                    } else {
                        if (dataSourceName.equals(prefix + "jta_datasource")) {
                            errorMsg += prefix + "jta_datasource was expected\n";
                        }
                    }
                }
            }
        }
    } finally {
        // clean-up
        if (isInTransaction) {
            rollbackTransaction(em);
        }
        if (em != null) {
            closeEntityManager(em);
        }
    }
    if (errorMsg.length() > 0) {
        fail(errorMsg);
    }
}
Also used : EntityManager(jakarta.persistence.EntityManager) JpaEntityManager(org.eclipse.persistence.jpa.JpaEntityManager) HashMap(java.util.HashMap) EntityManagerImpl(org.eclipse.persistence.internal.jpa.EntityManagerImpl) JpaEntityManagerFactory(org.eclipse.persistence.jpa.JpaEntityManagerFactory) EntityManagerFactory(jakarta.persistence.EntityManagerFactory) ClientSession(org.eclipse.persistence.sessions.server.ClientSession) SessionBroker(org.eclipse.persistence.sessions.broker.SessionBroker) JNDIConnector(org.eclipse.persistence.sessions.JNDIConnector) ConnectionPolicy(org.eclipse.persistence.sessions.server.ConnectionPolicy) Map(java.util.Map) HashMap(java.util.HashMap)

Example 9 with ConnectionPolicy

use of org.eclipse.persistence.sessions.server.ConnectionPolicy in project eclipselink by eclipse-ee4j.

the class EntityManagerJUnitTestSuite method internalTestPostAcquirePreReleaseEvents.

public void internalTestPostAcquirePreReleaseEvents(boolean useExternalConnectionPool) {
    if (isOnServer()) {
        // Uses DefaultConnector.
        return;
    }
    SessionBroker broker = ((JpaEntityManagerFactory) getEntityManagerFactory()).getSessionBroker();
    // Testing ExclusiveConnectionMode.Isolated requires a session that has isolated descriptors.
    ServerSession ss = (ServerSession) broker.getSessionForClass(Address.class);
    if (ss.getPlatform().isSybase()) {
        warning("Warning Sybase Driver does not work with DriverWrapper, testPostAcquirePreReleaseEvents can't run on this platform.");
        return;
    }
    if (ss.getPlatform().isSymfoware()) {
        warning("Test testPostAcquirePreReleaseEvents skipped for this platform, " + "Symfoware platform doesn't support failover.");
        return;
    }
    // normally false; set to true for debug output for just this single test
    boolean shouldForceFinest = false;
    int originalLogLevel = -1;
    // cache the original driver name and connection string.
    String originalDriverName = ss.getLogin().getDriverClassName();
    String originalConnectionString = ss.getLogin().getConnectionString();
    // cache original connector for external connection pool case
    Connector originalConnector = ss.getLogin().getConnector();
    // the new driver name and connection string to be used by the test
    String newDriverName = DriverWrapper.class.getName();
    String newConnectionString = DriverWrapper.codeUrl(originalConnectionString);
    // setup the wrapper driver
    DriverWrapper.initialize(originalDriverName);
    // The test need to connect with the new driver and connection string.
    // That could be done in JPA:
    // // close the existing emf
    // closeEntityManagerFactory();
    // HashMap properties = new HashMap(JUnitTestCaseHelper.getDatabaseProperties());
    // properties.put(PersistenceUnitProperties.JDBC_DRIVER, newDriverName);
    // properties.put(PersistenceUnitProperties.JDBC_URL, newConnectionString);
    // emf = getEntityManagerFactory(properties);
    // However this only works in case closeEntityManagerFactory disconnects the original ServerSession,
    // which requires the factory to be the only one using the persistence unit.
    // Alternative - and faster - approach is to disconnect the original session directly
    // and then reconnected it with the new driver and connection string.
    broker.logout();
    if (useExternalConnectionPool) {
        ss.getLogin().setConnector(new JNDIConnector(new DataSourceImpl(null, newConnectionString, null, null)));
        ss.getLogin().useExternalConnectionPooling();
    } else {
        ss.getLogin().setDriverClassName(newDriverName);
        ss.getLogin().setConnectionString(newConnectionString);
    }
    if (shouldForceFinest) {
        if (broker.getLogLevel() != SessionLog.FINEST) {
            originalLogLevel = broker.getLogLevel();
            broker.setLogLevel(SessionLog.FINEST);
        }
    }
    // switch off reconnection
    boolean originalIsConnectionHealthValidatedOnError = ss.getLogin().isConnectionHealthValidatedOnError();
    ss.getLogin().setConnectionHealthValidatedOnError(false);
    // Using DriverWrapper the listener will repair connection on postAcquireConnection and break it on preReleaseConnection event.
    // Also the listener will verify that neither postAcquireConnection nor preReleaseConnection events not called two in a row.
    AcquireRepair_ReleaseBreak_Listener listener = new AcquireRepair_ReleaseBreak_Listener();
    ss.getEventManager().addListener(listener);
    // Driver's connect method will still work, however any method called on any acquired connection will throw SQLException.
    // On postAcquireConnection connection will be repaired; on preReleaseConnection - broken again.
    broker.log(SessionLog.FINEST, SessionLog.CONNECTION, "testPostAcquirePreReleaseEvents: DriverWrapper.breakOldConnections(); DriverWrapper.breakNewConnections();", null, null, false);
    DriverWrapper.breakOldConnections();
    DriverWrapper.breakNewConnections();
    broker.login();
    // test several configurations:
    // all exclusive connection modes
    String[] exclusiveConnectionModeArray = new String[] { ExclusiveConnectionMode.Transactional, ExclusiveConnectionMode.Isolated, ExclusiveConnectionMode.Always };
    // Normally the user wishing to use not pooled connection would specify user and password properties (and possibly db url, too).
    // However if these properties have the same values that those in the logging then no non pooled connection is created and the pooled one used instead.
    // In the test we must use the same user as already in the session login (don't know any others) that forces usage of ConnectionPolicy property.
    ConnectionPolicy connectionPolicy = (ConnectionPolicy) ss.getDefaultConnectionPolicy().clone();
    connectionPolicy.setLogin(ss.getLogin());
    connectionPolicy.setPoolName(null);
    try {
        HashMap emProperties = new HashMap(1);
        HashMap mapOfProperties = new HashMap(1);
        emProperties.put(PersistenceUnitProperties.COMPOSITE_UNIT_PROPERTIES, mapOfProperties);
        HashMap memberProperties = new HashMap();
        mapOfProperties.put(ss.getName(), memberProperties);
        String mode, pooled = "", exclusiveConnectionMode;
        for (int k = 0; k < 2; k++) {
            if (k == 1) {
                // use non pooled connections
                pooled = "non pooled; ";
                memberProperties.put(EntityManagerProperties.CONNECTION_POLICY, connectionPolicy);
            }
            for (int i = 0; i < exclusiveConnectionModeArray.length; i++) {
                exclusiveConnectionMode = exclusiveConnectionModeArray[i];
                for (int j = 0; j < 3; j++) {
                    // either beginning early transaction or not
                    boolean shouldBeginEarlyTransaction = (j == 2);
                    boolean shouldReadBeforeTransaction = (j == 1);
                    mode = pooled + exclusiveConnectionMode + (shouldBeginEarlyTransaction ? "; beginEarlyTransaction" : "") + (shouldReadBeforeTransaction ? "; readBeforeTransaction" : "");
                    broker.log(SessionLog.FINEST, SessionLog.CONNECTION, "testPostAcquirePreReleaseEvents: " + mode, null, null, false);
                    memberProperties.put(EntityManagerProperties.EXCLUSIVE_CONNECTION_MODE, exclusiveConnectionMode);
                    EntityManager em = createEntityManager(emProperties);
                    if (shouldReadBeforeTransaction) {
                        em.find(Address.class, 1);
                    }
                    Address address = null;
                    try {
                        em.getTransaction().begin();
                        if (shouldBeginEarlyTransaction) {
                            em.unwrap(UnitOfWorkImpl.class).beginEarlyTransaction();
                        }
                        address = new Address();
                        address.setCountry("testPostAcquirePreReleaseEvents");
                        em.persist(address);
                        em.getTransaction().commit();
                    } finally {
                        // expected exception - connection is invalid and cannot be reconnected.
                        if (em.getTransaction().isActive()) {
                            em.getTransaction().rollback();
                        }
                        closeEntityManager(em);
                    }
                    if (listener.hasAcquiredConnections()) {
                        fail(mode + " connection was not passed to preReleaseConnection event");
                    }
                }
            }
        }
    } finally {
        // clear the driver wrapper
        DriverWrapper.clear();
        // reconnect the session using the original driver and connection string
        ss.getEventManager().removeListener(listener);
        // clean-up
        // remove the inserted object
        EntityManager em = createEntityManager();
        em.getTransaction().begin();
        try {
            em.createQuery("DELETE FROM Address a WHERE a.country = 'testPostAcquirePreReleaseEvents'");
            em.getTransaction().commit();
        } finally {
            if (em.getTransaction().isActive()) {
                em.getTransaction().rollback();
            }
            closeEntityManager(em);
            broker.logout();
            if (originalLogLevel >= 0) {
                broker.setLogLevel(originalLogLevel);
            }
            if (useExternalConnectionPool) {
                ss.getLogin().setConnector(originalConnector);
                ss.getLogin().dontUseExternalConnectionPooling();
            } else {
                ss.getLogin().setDriverClassName(originalDriverName);
                ss.getLogin().setConnectionString(originalConnectionString);
            }
            ss.getLogin().setConnectionHealthValidatedOnError(originalIsConnectionHealthValidatedOnError);
            broker.login();
        }
    }
}
Also used : Connector(org.eclipse.persistence.sessions.Connector) JNDIConnector(org.eclipse.persistence.sessions.JNDIConnector) ServerSession(org.eclipse.persistence.sessions.server.ServerSession) Address(org.eclipse.persistence.testing.models.jpa.composite.advanced.member_1.Address) HashMap(java.util.HashMap) DataSourceImpl(org.eclipse.persistence.internal.jpa.jdbc.DataSourceImpl) SessionBroker(org.eclipse.persistence.sessions.broker.SessionBroker) UnitOfWorkImpl(org.eclipse.persistence.internal.sessions.UnitOfWorkImpl) EntityManager(jakarta.persistence.EntityManager) JpaEntityManager(org.eclipse.persistence.jpa.JpaEntityManager) JpaEntityManagerFactory(org.eclipse.persistence.jpa.JpaEntityManagerFactory) JNDIConnector(org.eclipse.persistence.sessions.JNDIConnector) ConnectionPolicy(org.eclipse.persistence.sessions.server.ConnectionPolicy)

Example 10 with ConnectionPolicy

use of org.eclipse.persistence.sessions.server.ConnectionPolicy in project eclipselink by eclipse-ee4j.

the class EntityManagerJUnitTestSuite method testNonPooledConnection.

// Bug 332683 - Problems with ClientSession connections
// This test verifies that non pooled connection case works.
public void testNonPooledConnection() {
    String memberPuName = getCompositeMemberPuName(2);
    ServerSession ss = (ServerSession) getSessionBroker().getSessionForName(memberPuName);
    // Normally the user wishing to use not pooled connection would specify user and password properties (and possibly db url, too).
    // However if these properties have the same values that those in the logging then no non pooled connection is created and the pooled one used instead.
    // In the test we must use the same user as already in the session login (don't know any others) that forces usage of ConnectionPolicy property.
    ConnectionPolicy connectionPolicy = (ConnectionPolicy) ss.getDefaultConnectionPolicy().clone();
    connectionPolicy.setLogin(ss.getLogin());
    connectionPolicy.setPoolName(null);
    EntityManager em;
    boolean isEmInjected = isOnServer() && ss.getLogin().shouldUseExternalTransactionController();
    boolean isSpring = isOnServer() && getServerPlatform().isSpring();
    Map memberProperties = new HashMap(1);
    memberProperties.put(EntityManagerProperties.CONNECTION_POLICY, connectionPolicy);
    Map mapOfProperties = new HashMap(1);
    mapOfProperties.put(memberPuName, memberProperties);
    if (isEmInjected) {
        em = createEntityManager();
        // In server jta case need a transaction - otherwise the wrapped EntityManagerImpl is not kept.
        beginTransaction(em);
        em.setProperty(EntityManagerProperties.COMPOSITE_UNIT_PROPERTIES, mapOfProperties);
    } else {
        EntityManagerFactory emFactory = getEntityManagerFactory();
        Map properties = new HashMap(1);
        properties.put(EntityManagerProperties.COMPOSITE_UNIT_PROPERTIES, mapOfProperties);
        em = emFactory.createEntityManager(properties);
        if (isSpring) {
            em.getTransaction().begin();
        } else {
            beginTransaction(em);
        }
    }
    try {
        // native query triggers early begin transaction
        em.createNativeQuery("SELECT F_NAME FROM MBR2_EMPLOYEE").setHint(QueryHints.COMPOSITE_UNIT_MEMBER, memberPuName).getResultList();
        // verify that the connection is really not pooled.
        assertTrue("Test problem: connection should be not pooled", em.unwrap(UnitOfWork.class).getParent().getAccessor().getPool() == null);
    } finally {
        if (isSpring) {
            em.getTransaction().rollback();
        } else {
            rollbackTransaction(em);
        }
        closeEntityManager(em);
    }
}
Also used : UnitOfWork(org.eclipse.persistence.sessions.UnitOfWork) RepeatableWriteUnitOfWork(org.eclipse.persistence.internal.sessions.RepeatableWriteUnitOfWork) ServerSession(org.eclipse.persistence.sessions.server.ServerSession) EntityManager(jakarta.persistence.EntityManager) JpaEntityManager(org.eclipse.persistence.jpa.JpaEntityManager) HashMap(java.util.HashMap) JpaEntityManagerFactory(org.eclipse.persistence.jpa.JpaEntityManagerFactory) EntityManagerFactory(jakarta.persistence.EntityManagerFactory) ConnectionPolicy(org.eclipse.persistence.sessions.server.ConnectionPolicy) Map(java.util.Map) HashMap(java.util.HashMap)

Aggregations

ConnectionPolicy (org.eclipse.persistence.sessions.server.ConnectionPolicy)13 HashMap (java.util.HashMap)10 EntityManager (jakarta.persistence.EntityManager)9 ServerSession (org.eclipse.persistence.sessions.server.ServerSession)8 JpaEntityManager (org.eclipse.persistence.jpa.JpaEntityManager)6 JpaEntityManagerFactory (org.eclipse.persistence.jpa.JpaEntityManagerFactory)6 JNDIConnector (org.eclipse.persistence.sessions.JNDIConnector)5 EntityManagerFactory (jakarta.persistence.EntityManagerFactory)4 Map (java.util.Map)4 EntityTransaction (jakarta.persistence.EntityTransaction)3 EntityManagerFactoryImpl (org.eclipse.persistence.internal.jpa.EntityManagerFactoryImpl)3 Dog (org.eclipse.persistence.jpa.test.basic.model.Dog)3 Person (org.eclipse.persistence.jpa.test.basic.model.Person)3 XmlFish (org.eclipse.persistence.jpa.test.basic.model.XmlFish)3 UnitOfWork (org.eclipse.persistence.sessions.UnitOfWork)3 Test (org.junit.Test)3 EntityManagerImpl (org.eclipse.persistence.internal.jpa.EntityManagerImpl)2 DataSourceImpl (org.eclipse.persistence.internal.jpa.jdbc.DataSourceImpl)2 RepeatableWriteUnitOfWork (org.eclipse.persistence.internal.sessions.RepeatableWriteUnitOfWork)2 UnitOfWorkImpl (org.eclipse.persistence.internal.sessions.UnitOfWorkImpl)2