Search in sources :

Example 21 with DatabaseSessionImpl

use of org.eclipse.persistence.internal.sessions.DatabaseSessionImpl in project eclipselink by eclipse-ee4j.

the class EntityMappingsAdvancedJUnitTestCase method testUnidirectionalUpdate.

public void testUnidirectionalUpdate() {
    String lastName = "testUnidirectionalUpdate";
    // em used for both persist and update
    EntityManager em = createEntityManager();
    // persist employees
    List<Employee> employeesPersisted = persistEmployeesWithUnidirectionalMappings(lastName, em);
    // update persisted employees:
    beginTransaction(em);
    try {
        // add a new dealer to the first employee
        employeesPersisted.get(0).addDealer(new Dealer("New", lastName));
        // remove a dealer from the second employee
        employeesPersisted.get(1).getDealers().remove(1);
        // move a dealer from the first to the second employee
        employeesPersisted.get(1).addDealer(employeesPersisted.get(0).getDealers().remove(0));
        commitTransaction(em);
    } finally {
        if (this.isTransactionActive(em)) {
            rollbackTransaction(em);
        }
        closeEntityManager(em);
    }
    // clear cache
    clearCache();
    em = createEntityManager();
    // read the updated employees back
    List<Employee> employeesRead = em.createQuery("SELECT OBJECT(e) FROM XMLEmployee e WHERE e.lastName = '" + lastName + "'").getResultList();
    // while em is open, cache ServerSession that will be used later for verification
    DatabaseSessionImpl session = getDatabaseSession();
    // verify number persisted and read is the same
    if (employeesPersisted.size() != employeesRead.size()) {
        // clean-up
        deleteEmployeesWithUnidirectionalMappings(lastName);
        fail("Updated " + employeesPersisted.size() + " employees, but read back " + employeesRead.size());
    }
    // verify that the persisted and read objects are equal
    beginTransaction(em);
    String errorMsg = "";
    try {
        for (int i = 0; i < employeesPersisted.size(); i++) {
            for (int j = 0; j < employeesRead.size(); j++) {
                Employee emp1 = em.find(Employee.class, employeesPersisted.get(i).getId());
                Employee emp2 = em.find(Employee.class, employeesRead.get(j).getId());
                if (emp1.getFirstName().equals(emp2.getFirstName())) {
                    if (!session.compareObjects(emp1, emp2)) {
                        errorMsg += "Employee " + emp1.getFirstName() + "  was not updated correctly.";
                    }
                }
            }
        }
    } finally {
        if (this.isTransactionActive(em)) {
            rollbackTransaction(em);
        }
        closeEntityManager(em);
    }
    // clean-up
    deleteEmployeesWithUnidirectionalMappings(lastName);
    // non-empty error message means the test has failed
    if (errorMsg.length() > 0) {
        fail(errorMsg);
    }
}
Also used : EntityManager(jakarta.persistence.EntityManager) Employee(org.eclipse.persistence.testing.models.jpa.xml.composite.advanced.member_2.Employee) DatabaseSessionImpl(org.eclipse.persistence.internal.sessions.DatabaseSessionImpl) Dealer(org.eclipse.persistence.testing.models.jpa.xml.composite.advanced.member_3.Dealer)

Example 22 with DatabaseSessionImpl

use of org.eclipse.persistence.internal.sessions.DatabaseSessionImpl in project eclipselink by eclipse-ee4j.

the class EntityMappingsAdvancedJUnitTestCase method testUnidirectionalFetchJoin.

public void testUnidirectionalFetchJoin() {
    String lastName = "testUnidirectionalFetchJoin";
    // persist employees
    persistEmployeesWithUnidirectionalMappings(lastName);
    // clear cache
    clearCache();
    EntityManager em = createEntityManager();
    // read the persisted employees back - without fetch join
    List<Employee> employeesRead = em.createQuery("SELECT OBJECT(e) FROM XMLEmployee e WHERE e.lastName = '" + lastName + "'").getResultList();
    closeEntityManager(em);
    // clear cache
    clearCache();
    // read the persisted employees back - with fetch join.
    em = createEntityManager();
    List<Employee> employeesReadWithFetchJoin = em.createQuery("SELECT e FROM XMLEmployee e JOIN FETCH e.dealers WHERE e.lastName = '" + lastName + "'").getResultList();
    // while em is open, cache ServerSession that will be used later for verification
    DatabaseSessionImpl session = getDatabaseSession();
    closeEntityManager(em);
    // verify that the persisted and read employees are the same.
    // The comparison cascades to all references and requires the same state of indirection:
    // it fails in case an object has triggered indirection for particular attribute and compared object's indirection for this attribute is not triggered.
    // The expected result of join fetch query is Employee.dealers being triggered - so need to trigger it on the control collection (getDealers.size() does that);
    // also the expected result should have an object for each row returned - therefore number of inclusions of each Employee equals its dealers.size()
    List<Employee> employeesControl = new ArrayList<Employee>();
    for (int i = 0; i < employeesRead.size(); i++) {
        int nDialers = employeesRead.get(i).getDealers().size();
        for (int j = 0; j < nDialers; j++) {
            employeesControl.add(employeesRead.get(i));
        }
    }
    String errorMsg = JoinedAttributeTestHelper.compareCollections(employeesControl, employeesReadWithFetchJoin, session.getClassDescriptor(Employee.class), session);
    // clean-up
    deleteEmployeesWithUnidirectionalMappings(lastName);
    // non-empty error message means the test has failed
    if (errorMsg.length() > 0) {
        fail(errorMsg);
    }
}
Also used : EntityManager(jakarta.persistence.EntityManager) Employee(org.eclipse.persistence.testing.models.jpa.xml.composite.advanced.member_2.Employee) DatabaseSessionImpl(org.eclipse.persistence.internal.sessions.DatabaseSessionImpl) ArrayList(java.util.ArrayList)

Example 23 with DatabaseSessionImpl

use of org.eclipse.persistence.internal.sessions.DatabaseSessionImpl in project eclipselink by eclipse-ee4j.

the class EntityMappingsAdvancedJUnitTestCase method testProjectChangeTrackingPolicy.

/**
 * Verifies that the change tracking metadata is correctly processed.
 */
public void testProjectChangeTrackingPolicy() {
    if (!isWeavingEnabled()) {
        return;
    }
    DatabaseSessionImpl session = getDatabaseSession();
    ClassDescriptor descriptor = session.getDescriptor(Project.class);
    assertFalse("Project descriptor was not found in the PU [" + m_persistenceUnit + "]", descriptor == null);
    assertTrue("Project descriptor has incorrect object change policy", descriptor.getObjectChangePolicy().isObjectChangeTrackingPolicy());
}
Also used : ClassDescriptor(org.eclipse.persistence.descriptors.ClassDescriptor) DatabaseSessionImpl(org.eclipse.persistence.internal.sessions.DatabaseSessionImpl)

Example 24 with DatabaseSessionImpl

use of org.eclipse.persistence.internal.sessions.DatabaseSessionImpl in project eclipselink by eclipse-ee4j.

the class EntityMappingsAdvancedJUnitTestCase method testProjectOptimisticLockingSettings.

/**
 * Verifies that the optimistic-locking settings were read correctly from XML.
 */
public void testProjectOptimisticLockingSettings() {
    DatabaseSessionImpl session = getDatabaseSession();
    ClassDescriptor descriptor = session.getDescriptor(Project.class);
    if (descriptor == null) {
        fail("Project descriptor was not found in the PU [" + m_persistenceUnit + "]");
    } else {
        OptimisticLockingPolicy policy = descriptor.getOptimisticLockingPolicy();
        if (policy instanceof SelectedFieldsLockingPolicy) {
            List<DatabaseField> lockFields = ((SelectedFieldsLockingPolicy) policy).getLockFields();
            if (lockFields.isEmpty() || lockFields.size() > 1) {
                fail("Invalid amount of lock fields were set on Project's selected fields locking policy.");
            } else {
                DatabaseField lockField = lockFields.get(0);
                assertTrue("Incorrect lock field was set on Project's selected fields locking policy.", lockField.getName().equals("VERSION"));
            }
        } else {
            fail("A SelectedFieldsLockingPolicy was not set on the Project descriptor.");
        }
    }
}
Also used : SelectedFieldsLockingPolicy(org.eclipse.persistence.descriptors.SelectedFieldsLockingPolicy) ClassDescriptor(org.eclipse.persistence.descriptors.ClassDescriptor) DatabaseSessionImpl(org.eclipse.persistence.internal.sessions.DatabaseSessionImpl) DatabaseField(org.eclipse.persistence.internal.helper.DatabaseField) OptimisticLockingPolicy(org.eclipse.persistence.internal.descriptors.OptimisticLockingPolicy)

Example 25 with DatabaseSessionImpl

use of org.eclipse.persistence.internal.sessions.DatabaseSessionImpl in project eclipselink by eclipse-ee4j.

the class EntityManagerJUnitTestSuite method testPESSIMISTIC_READ_TIMEOUTLock.

public void testPESSIMISTIC_READ_TIMEOUTLock() {
    DatabaseSessionImpl session = getDatabaseSession();
    // Lock timeout is only supported on Oracle.
    if (!isOnServer() && session.getPlatform().isOracle()) {
        EntityManager em = createEntityManager();
        List result = em.createQuery("Select employee from Employee employee").getResultList();
        Employee employee = (Employee) result.get(0);
        Exception lockTimeOutException = null;
        try {
            beginTransaction(em);
            employee = em.find(Employee.class, employee.getId(), LockModeType.PESSIMISTIC_READ);
            EntityManager em2 = createEntityManager();
            try {
                beginTransaction(em2);
                HashMap<String, Object> properties = new HashMap<String, Object>();
                properties.put(QueryHints.PESSIMISTIC_LOCK_TIMEOUT, 5000);
                Employee employee2 = em2.find(Employee.class, employee.getId(), LockModeType.PESSIMISTIC_READ, properties);
                employee2.setFirstName("Invalid Lock Employee");
                commitTransaction(em2);
            } catch (PersistenceException ex) {
                if (isTransactionActive(em2)) {
                    rollbackTransaction(em2);
                }
                if (ex instanceof jakarta.persistence.LockTimeoutException) {
                    lockTimeOutException = ex;
                } else {
                    throw ex;
                }
            } finally {
                closeEntityManager(em2);
            }
            commitTransaction(em);
        } catch (RuntimeException ex) {
            if (isTransactionActive(em)) {
                rollbackTransaction(em);
            }
            throw ex;
        } finally {
            closeEntityManager(em);
        }
        assertFalse("Proper exception not thrown when Query with LockModeType.PESSIMISTIC is used.", lockTimeOutException == null);
    }
}
Also used : HashMap(java.util.HashMap) TestProblemException(org.eclipse.persistence.testing.framework.TestProblemException) IntegrityException(org.eclipse.persistence.exceptions.IntegrityException) EntityNotFoundException(jakarta.persistence.EntityNotFoundException) ValidationException(org.eclipse.persistence.exceptions.ValidationException) EclipseLinkException(org.eclipse.persistence.exceptions.EclipseLinkException) EntityExistsException(jakarta.persistence.EntityExistsException) OptimisticLockException(jakarta.persistence.OptimisticLockException) RollbackException(jakarta.persistence.RollbackException) PersistenceException(jakarta.persistence.PersistenceException) QueryException(org.eclipse.persistence.exceptions.QueryException) TransactionRequiredException(jakarta.persistence.TransactionRequiredException) EntityManager(jakarta.persistence.EntityManager) JpaEntityManager(org.eclipse.persistence.jpa.JpaEntityManager) Employee(org.eclipse.persistence.testing.models.jpa.composite.advanced.member_2.Employee) DatabaseSessionImpl(org.eclipse.persistence.internal.sessions.DatabaseSessionImpl) PersistenceException(jakarta.persistence.PersistenceException) IndirectList(org.eclipse.persistence.indirection.IndirectList) ArrayList(java.util.ArrayList) List(java.util.List)

Aggregations

DatabaseSessionImpl (org.eclipse.persistence.internal.sessions.DatabaseSessionImpl)64 ClassDescriptor (org.eclipse.persistence.descriptors.ClassDescriptor)18 EntityManager (jakarta.persistence.EntityManager)15 HashMap (java.util.HashMap)14 DatabaseSession (org.eclipse.persistence.sessions.DatabaseSession)14 Map (java.util.Map)13 DatabaseLogin (org.eclipse.persistence.sessions.DatabaseLogin)13 Project (org.eclipse.persistence.sessions.Project)12 StringReader (java.io.StringReader)9 StreamSource (javax.xml.transform.stream.StreamSource)9 Platform (org.eclipse.persistence.internal.databaseaccess.Platform)9 MetadataProcessor (org.eclipse.persistence.internal.jpa.metadata.MetadataProcessor)9 AbstractSession (org.eclipse.persistence.internal.sessions.AbstractSession)9 XMLContext (org.eclipse.persistence.oxm.XMLContext)9 DatasourceLogin (org.eclipse.persistence.sessions.DatasourceLogin)9 JAXBContext (jakarta.xml.bind.JAXBContext)8 JAXBException (jakarta.xml.bind.JAXBException)8 Unmarshaller (jakarta.xml.bind.Unmarshaller)8 ConversionManager (org.eclipse.persistence.internal.helper.ConversionManager)8 XRDynamicClassLoader (org.eclipse.persistence.internal.xr.XRDynamicClassLoader)8