Search in sources :

Example 26 with EntityManagerImpl

use of org.eclipse.persistence.internal.jpa.EntityManagerImpl in project eclipselink by eclipse-ee4j.

the class TestTimestampVersionLocking method testLocalTimestampPropertyFalseCustomizer.

/**
 * Check that setting the value LOCAL on the OptimisticLockingPolicy in a
 * DescriptorCustomizer will override the persistence property value.
 */
@Test
public void testLocalTimestampPropertyFalseCustomizer() throws Exception {
    // Have policy customized to use local time
    ClassDescriptorCustomizer.USETIME = TimestampLockingPolicy.LOCAL_TIME;
    EntityManager em = emfFalseCustomized.createEntityManager();
    try {
        em.getTransaction().begin();
        // Get the session for this transaction
        Session session = ((EntityManagerImpl) em).getActiveSession();
        // Get the TimestampQuery that would be used by the platform to get the current time
        DatabaseQuery query = session.getDatasourcePlatform().getTimestampQuery();
        // Add a Listener to the session
        QueryListener listener = new QueryListener(query);
        session.getEventManager().addListener(listener);
        // Persist an Entity that will use Timestamp version locking and will trigger QueryListener
        TimestampDog dog = new TimestampDog();
        em.persist(dog);
        em.getTransaction().commit();
        // Make sure the query was not executed
        Assert.assertTrue("Query (" + listener.getQuery().getSQLString() + ") was executed unexpectedly.", !listener.wasQueryExecuted());
    } finally {
        if (em.getTransaction().isActive()) {
            em.getTransaction().rollback();
        }
    }
}
Also used : EntityManager(jakarta.persistence.EntityManager) DatabaseQuery(org.eclipse.persistence.queries.DatabaseQuery) EntityManagerImpl(org.eclipse.persistence.internal.jpa.EntityManagerImpl) TimestampDog(org.eclipse.persistence.jpa.test.locking.model.TimestampDog) Session(org.eclipse.persistence.sessions.Session) Test(org.junit.Test)

Example 27 with EntityManagerImpl

use of org.eclipse.persistence.internal.jpa.EntityManagerImpl in project eclipselink by eclipse-ee4j.

the class TestTimestampVersionLocking method testLocalTimestampPropertyFalse.

/**
 * Check that setting the property "false" will get the server system time
 * just like the default behavior.
 */
@Test
public void testLocalTimestampPropertyFalse() throws Exception {
    EntityManager em = emfFalse.createEntityManager();
    try {
        em.getTransaction().begin();
        // Get the session for this transaction
        Session session = ((EntityManagerImpl) em).getActiveSession();
        // Get the TimestampQuery that would be used by the platform to get the current time
        DatabaseQuery query = session.getDatasourcePlatform().getTimestampQuery();
        // Add a Listener to the session
        QueryListener listener = new QueryListener(query);
        session.getEventManager().addListener(listener);
        // Persist an Entity that will use Timestamp version locking and will trigger QueryListener
        TimestampDog dog = new TimestampDog();
        em.persist(dog);
        em.getTransaction().commit();
        // Make sure the query was not executed
        Assert.assertTrue("Query (" + listener.getQuery().getSQLString() + ") was executed unexpectedly.", listener.wasQueryExecuted());
    } finally {
        if (em.getTransaction().isActive()) {
            em.getTransaction().rollback();
        }
    }
}
Also used : EntityManager(jakarta.persistence.EntityManager) DatabaseQuery(org.eclipse.persistence.queries.DatabaseQuery) EntityManagerImpl(org.eclipse.persistence.internal.jpa.EntityManagerImpl) TimestampDog(org.eclipse.persistence.jpa.test.locking.model.TimestampDog) Session(org.eclipse.persistence.sessions.Session) Test(org.junit.Test)

Example 28 with EntityManagerImpl

use of org.eclipse.persistence.internal.jpa.EntityManagerImpl in project eclipselink by eclipse-ee4j.

the class TestMultitenantOneToMany method setup.

@Before
public void setup() {
    EntityManager em = emf.createEntityManager();
    // MySQL only due permissions for CREATE SCHEMA command.
    if (((EntityManagerImpl) em).getDatabaseSession().getPlatform().isMySQL()) {
        supportedPlatform = true;
        try {
            em.getTransaction().begin();
            em.createNativeQuery("DROP SCHEMA IF EXISTS tenant_1").executeUpdate();
            em.createNativeQuery("DROP SCHEMA IF EXISTS tenant_2").executeUpdate();
            em.createNativeQuery("CREATE SCHEMA tenant_1").executeUpdate();
            em.createNativeQuery("CREATE SCHEMA tenant_2").executeUpdate();
            em.createNativeQuery("CREATE TABLE tenant_1.parent(id bigint primary key)").executeUpdate();
            em.createNativeQuery("CREATE TABLE tenant_2.parent(id bigint primary key)").executeUpdate();
            em.createNativeQuery("CREATE TABLE tenant_1.children(id bigint NOT NULL, parent_id bigint, PRIMARY KEY " + "(id), CONSTRAINT parent_fkey FOREIGN KEY (parent_id) REFERENCES tenant_1.parent (id))").executeUpdate();
            em.createNativeQuery("CREATE TABLE tenant_2.children(id bigint NOT NULL, parent_id bigint, PRIMARY KEY " + "(id), CONSTRAINT parent_fkey FOREIGN KEY (parent_id) REFERENCES tenant_2.parent (id))").executeUpdate();
            em.createNativeQuery("INSERT INTO tenant_1.parent(id) VALUES(1)").executeUpdate();
            em.createNativeQuery("INSERT INTO tenant_2.parent(id) VALUES(2)").executeUpdate();
            em.createNativeQuery("INSERT INTO tenant_1.children(id, parent_id) VALUES(10, 1)").executeUpdate();
            em.createNativeQuery("INSERT INTO tenant_2.children(id, parent_id) VALUES(11, 2)").executeUpdate();
            em.getTransaction().commit();
        } finally {
            if (em.getTransaction().isActive()) {
                em.getTransaction().rollback();
            }
            if (em.isOpen()) {
                em.close();
            }
        }
    }
}
Also used : EntityManager(jakarta.persistence.EntityManager) EntityManagerImpl(org.eclipse.persistence.internal.jpa.EntityManagerImpl) Before(org.junit.Before)

Example 29 with EntityManagerImpl

use of org.eclipse.persistence.internal.jpa.EntityManagerImpl in project eclipselink by eclipse-ee4j.

the class EntityManagerJUnitTestSuite method testDetachRemovedObject.

// detach(object) on a removed object does not throw exception. This test only
// checks whether an removed object is completely deleted from the
// getDeletedObject()Map after 'detach(removedobject)' is invoked
public void testDetachRemovedObject() {
    // create an Employee
    Employee emp = new Employee();
    emp.setFirstName("testDetachRemovedObjectEmployee");
    // persist the Employee
    EntityManager em = createEntityManager();
    try {
        beginTransaction(em);
        em.persist(emp);
        commitTransaction(em);
    } catch (RuntimeException re) {
        if (isTransactionActive(em)) {
            rollbackTransaction(em);
        }
        throw re;
    }
    beginTransaction(em);
    // attempt to remove the Employee
    em.remove(em.find(Employee.class, emp.getId()));
    commitTransaction(em);
    beginTransaction(em);
    EntityManagerImpl em1 = (EntityManagerImpl) em.getDelegate();
    try {
        // attempt to detach the Employee
        em.detach(emp);
        UnitOfWork uow = em1.getUnitOfWork();
        UnitOfWorkImpl uowImpl = (UnitOfWorkImpl) uow;
        boolean afterClear = uowImpl.getDeletedObjects().containsKey(emp);
        assertFalse("exception thrown when detaching a removed entity is attempted.", afterClear);
    } catch (IllegalArgumentException iae) {
        return;
    } finally {
        if (isTransactionActive(em)) {
            rollbackTransaction(em);
        }
        closeEntityManager(em);
    }
}
Also used : UnitOfWork(org.eclipse.persistence.sessions.UnitOfWork) RepeatableWriteUnitOfWork(org.eclipse.persistence.internal.sessions.RepeatableWriteUnitOfWork) EntityManager(jakarta.persistence.EntityManager) JpaEntityManager(org.eclipse.persistence.jpa.JpaEntityManager) Employee(org.eclipse.persistence.testing.models.jpa.composite.advanced.member_2.Employee) EntityManagerImpl(org.eclipse.persistence.internal.jpa.EntityManagerImpl) UnitOfWorkImpl(org.eclipse.persistence.internal.sessions.UnitOfWorkImpl)

Example 30 with EntityManagerImpl

use of org.eclipse.persistence.internal.jpa.EntityManagerImpl in project eclipselink by eclipse-ee4j.

the class EntityManagerJUnitTestSuite method testEMFactoryCloseAndOpen.

// Bug 256284: Closing an EMF where the database is unavailable results in deployment exception on redeploy
public void testEMFactoryCloseAndOpen() {
    if (isOnServer()) {
        // Uses DefaultConnector.
        return;
    }
    // Assert.assertFalse("Warning Sybase Driver does not work with DriverWrapper, testEMCloseAndOpen can't run on this platform.",  getPlatform(Employee.class).isSybase());
    SessionBroker broker = ((JpaEntityManagerFactory) getEntityManagerFactory()).getSessionBroker();
    ServerSession ss = (ServerSession) broker.getSessionForClass(Employee.class);
    // cache the driver name
    String driverName = ss.getLogin().getDriverClassName();
    String originalConnectionString = ss.getLogin().getConnectionString();
    // disconnect the session
    closeEntityManagerFactory();
    // setup the wrapper driver
    DriverWrapper.initialize(driverName);
    // connect the session using the wrapper driver
    HashMap properties = new HashMap(JUnitTestCaseHelper.getDatabaseProperties(getPersistenceUnitName()));
    Map mapOfProperties = (Map) properties.get(PersistenceUnitProperties.COMPOSITE_UNIT_PROPERTIES);
    if (mapOfProperties == null) {
        mapOfProperties = new HashMap(1);
    } else {
        mapOfProperties = new HashMap(mapOfProperties);
    }
    properties.put(PersistenceUnitProperties.COMPOSITE_UNIT_PROPERTIES, mapOfProperties);
    Map memberProperties = (Map) mapOfProperties.get(ss.getName());
    if (memberProperties == null) {
        memberProperties = new HashMap(2);
    } else {
        memberProperties = new HashMap(memberProperties);
    }
    mapOfProperties.put(ss.getName(), memberProperties);
    memberProperties.put(PersistenceUnitProperties.JDBC_DRIVER, DriverWrapper.class.getName());
    memberProperties.put(PersistenceUnitProperties.JDBC_URL, DriverWrapper.codeUrl(originalConnectionString));
    getEntityManagerFactory(properties);
    // this connects the session
    EntityManager em = createEntityManager();
    // imitate disconnecting from network:
    // driver's connect method and any method on any connection will throw SQLException
    DriverWrapper.breakDriver();
    DriverWrapper.breakOldConnections();
    // close factory
    try {
        closeEntityManagerFactory();
    } finally {
        // clear the driver wrapper
        DriverWrapper.clear();
    }
    String errorMsg = "";
    // reconnect the session
    em = createEntityManager();
    // verify connections
    Iterator<ConnectionPool> itPools = ((ServerSession) ((EntityManagerImpl) em).getSessionBroker().getSessionForName(ss.getName())).getConnectionPools().values().iterator();
    while (itPools.hasNext()) {
        ConnectionPool pool = itPools.next();
        int disconnected = 0;
        for (int i = 0; i < pool.getConnectionsAvailable().size(); i++) {
            if (!(pool.getConnectionsAvailable().get(i)).isConnected()) {
                disconnected++;
            }
        }
        if (disconnected > 0) {
            errorMsg += pool.getName() + " has " + disconnected + " connections; ";
        }
    }
    if (errorMsg.length() > 0) {
        fail(errorMsg);
    }
}
Also used : ConnectionPool(org.eclipse.persistence.sessions.server.ConnectionPool) ServerSession(org.eclipse.persistence.sessions.server.ServerSession) DriverWrapper(org.eclipse.persistence.testing.framework.DriverWrapper) HashMap(java.util.HashMap) EntityManagerImpl(org.eclipse.persistence.internal.jpa.EntityManagerImpl) SessionBroker(org.eclipse.persistence.sessions.broker.SessionBroker) EntityManager(jakarta.persistence.EntityManager) JpaEntityManager(org.eclipse.persistence.jpa.JpaEntityManager) Employee(org.eclipse.persistence.testing.models.jpa.composite.advanced.member_2.Employee) JpaEntityManagerFactory(org.eclipse.persistence.jpa.JpaEntityManagerFactory) Map(java.util.Map) HashMap(java.util.HashMap)

Aggregations

EntityManagerImpl (org.eclipse.persistence.internal.jpa.EntityManagerImpl)38 EntityManager (jakarta.persistence.EntityManager)32 JpaEntityManager (org.eclipse.persistence.jpa.JpaEntityManager)13 PersistenceException (jakarta.persistence.PersistenceException)7 QueryException (org.eclipse.persistence.exceptions.QueryException)7 RepeatableWriteUnitOfWork (org.eclipse.persistence.internal.sessions.RepeatableWriteUnitOfWork)7 UnitOfWorkImpl (org.eclipse.persistence.internal.sessions.UnitOfWorkImpl)7 UnitOfWork (org.eclipse.persistence.sessions.UnitOfWork)7 HashMap (java.util.HashMap)6 ReadAllQuery (org.eclipse.persistence.queries.ReadAllQuery)6 ReadObjectQuery (org.eclipse.persistence.queries.ReadObjectQuery)6 Session (org.eclipse.persistence.sessions.Session)6 ArrayList (java.util.ArrayList)5 Map (java.util.Map)5 DatabaseQuery (org.eclipse.persistence.queries.DatabaseQuery)5 Query (jakarta.persistence.Query)4 Collection (java.util.Collection)4 ClassDescriptor (org.eclipse.persistence.descriptors.ClassDescriptor)4 DatabaseSession (org.eclipse.persistence.sessions.DatabaseSession)4 Test (org.junit.Test)4