Search in sources :

Example 1 with EntityManagerImpl

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

the class CallbackEventTest method setup.

@Override
public void setup() {
    super.setup();
    this.reset = true;
    // Stick an employee in there, re-used in sub tests.
    m_employee = new Employee();
    m_project = new SmallProject();
    try {
        beginTransaction();
        m_employee.setFirstName("Guy");
        m_employee.setLastName("Pelletier");
        getEntityManager().persist(m_employee);
        m_project.setName("A tiny project");
        m_project.setDescription("Must be an easy one");
        getEntityManager().persist(m_project);
        commitTransaction();
    } catch (Exception ex) {
        rollbackTransaction();
        throw new TestErrorException("Exception thrown during setup try to create an employee" + ex);
    }
    // Clear the cache so we are working from scratch.
    ((EntityManagerImpl) getEntityManager()).getActiveSession().getIdentityMapAccessor().initializeAllIdentityMaps();
}
Also used : EntityManagerImpl(org.eclipse.persistence.internal.jpa.EntityManagerImpl) TestErrorException(org.eclipse.persistence.testing.framework.TestErrorException) TestErrorException(org.eclipse.persistence.testing.framework.TestErrorException)

Example 2 with EntityManagerImpl

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

the class EntityManagerJUnitTestSuite method internalTestChangeRecordKeepOldValue.

public void internalTestChangeRecordKeepOldValue(boolean addSecondStep) {
    if (isOnServer()) {
        // the test relies upon keeping attached objects between transactions.
        return;
    }
    DatabaseSessionImpl dbs = getDatabaseSession();
    ChangeRecordKeepOldValueListener listener = new ChangeRecordKeepOldValueListener();
    dbs.getEventManager().addListener(listener);
    EntityManager em = createEntityManager();
    try {
        // setup
        // create original object and referenced objects
        Employee emp = new Employee();
        emp.setFirstName("TestChangeRecordKeepOldValue");
        emp.setLastName("Manager_OriginalName");
        emp.setMale();
        emp.setSalary(35000);
        emp.setPeriod(new EmploymentPeriod(Helper.dateFromYearMonthDate(1993, 0, 1), Helper.dateFromYearMonthDate(1996, 11, 31)));
        emp.setFormerEmployment(new FormerEmployment("Original", new EmploymentPeriod(Helper.dateFromYearMonthDate(1990, 0, 1), Helper.dateFromYearMonthDate(1993, 11, 31))));
        Address address = new Address();
        address.setCountry("Original");
        address.setProvince("Original");
        address.setCity("Original");
        address.setStreet("Original");
        address.setPostalCode("Original");
        emp.setAddress(address);
        Department dep = new Department();
        dep.setName("Original");
        emp.setDepartment(dep);
        emp.addResponsibility("Original_1");
        emp.addResponsibility("Original_2");
        PhoneNumber phone1 = new PhoneNumber("Original_1", "111", "1111111");
        emp.addPhoneNumber(phone1);
        PhoneNumber phone2 = new PhoneNumber("Original_2", "222", "2222222");
        emp.addPhoneNumber(phone2);
        emp.setNormalHours(new Time[] { Helper.timeFromHourMinuteSecond(9, 0, 0), Helper.timeFromHourMinuteSecond(17, 0, 0) });
        Employee emp1 = new Employee();
        emp1.setFirstName("TestChangeRecordKeepOldValue");
        emp1.setLastName("Original_1");
        emp.addManagedEmployee(emp1);
        Employee emp2 = new Employee();
        emp2.setFirstName("TestChangeRecordKeepOldValue");
        emp2.setLastName("Original_2");
        emp.addManagedEmployee(emp2);
        Project proj1 = new SmallProject();
        proj1.setName("Original_1");
        emp.addProject(proj1);
        Project proj2 = new LargeProject();
        proj2.setName("Original_2");
        emp.addProject(proj2);
        Project proj3 = new LargeProject();
        proj3.setName("Original_3");
        proj3.setTeamLeader(emp);
        emp1.addProject(proj3);
        emp2.addProject(proj3);
        // persist original object and all referenced objects
        beginTransaction(em);
        Equipment equipment1 = new Equipment();
        equipment1.setDescription("Original_1");
        // persist is not cascaded for department.equipment - have to explicitly persist it.
        em.persist(equipment1);
        dep.addEquipment(equipment1);
        Equipment equipment2 = new Equipment();
        equipment2.setDescription("Original_2");
        // persist is not cascaded for department.equipment - have to explicitly persist it.
        // moreover, equipment.id is used as a key in dep.equipment Map, therefore equipmet
        // should be persisted before been added to dep.
        em.persist(equipment2);
        dep.addEquipment(equipment2);
        // persist is not cascaded for employee.department - have to explicitly persist it.
        // moreover, equipment.id is used as a key in dep.equipment Map, therefore equipmet
        // should be persisted before been added to dep.
        em.persist(dep);
        em.persist(emp);
        commitTransaction(em);
        // backup original object and all referenced objects
        CopyGroup copyGroupBackup = new CopyGroup();
        copyGroupBackup.cascadeAllParts();
        dbs.copy(emp, copyGroupBackup);
        // emp references (directly or through other objects) all the created objects, therefore all of them are copied.
        Map backupMap = copyGroupBackup.getCopies();
        // verify that backup objects are identical to originals
        Iterator<Map.Entry> it = backupMap.entrySet().iterator();
        while (it.hasNext()) {
            Map.Entry entry = it.next();
            Object original = entry.getKey();
            ClassDescriptor descriptor = dbs.getDescriptor(original);
            if (!descriptor.isAggregateDescriptor()) {
                Object backup = entry.getValue();
                if (original == backup) {
                    fail("Test problem: backup failed: original == backup: " + original);
                }
                if (!dbs.compareObjects(original, backup)) {
                    fail("Test problem: backup failed: compareObjects(original, backup) == false: " + original + "; " + backup);
                }
            }
        }
        // change original object
        beginTransaction(em);
        // DirectToField
        emp.setLastName("Manager_NewName");
        // DirectToField
        emp.setSalary(100);
        // Aggregate
        emp.getPeriod().setStartDate(Helper.dateFromYearMonthDate(2000, 0, 1));
        emp.getPeriod().setEndDate(Helper.dateFromYearMonthDate(2002, 0, 1));
        // Aggregate
        // emp.setFormerEmployment(new FormerEmployment("New", new EmploymentPeriod(Helper.dateFromYearMonthDate(1989, 0, 1), Helper.dateFromYearMonthDate(1992, 11, 31))));
        emp.getFormerEmployment().setFormerCompany("New");
        emp.getFormerEmployment().getPeriod().setStartDate(Helper.dateFromYearMonthDate(1989, 0, 1));
        emp.getFormerEmployment().getPeriod().setStartDate(Helper.dateFromYearMonthDate(1992, 11, 31));
        // Transformation
        emp.setStartTime(Helper.timeFromHourMinuteSecond(10, 0, 0));
        // DirectCollection
        emp.removeResponsibility("Original_1");
        emp.addResponsibility("New_1");
        // Private Collection 1 to many
        PhoneNumber phone1New = new PhoneNumber("New_1", "111", "1111111");
        emp.addPhoneNumber(phone1New);
        emp.removePhoneNumber(phone1);
        // Collection 1 to many
        emp.removeManagedEmployee(emp1);
        emp1.setManager(null);
        em.remove(emp1);
        Employee emp1New = new Employee();
        emp1New.setFirstName("TestChangeRecordKeepOldValue");
        emp1New.setLastName("New_1");
        emp1New.addProject(proj3);
        emp.addManagedEmployee(emp1New);
        // Collection many to many
        emp.removeProject(proj1);
        em.remove(proj1);
        Project proj1New = new LargeProject();
        proj1New.setName("New_1");
        emp.addProject(proj1New);
        // ObjectReference
        proj3.setTeamLeader(null);
        // ObjectReference
        Address addressNew = new Address();
        addressNew.setCountry("New");
        addressNew.setProvince("New");
        addressNew.setCity("New");
        addressNew.setStreet("New");
        addressNew.setPostalCode("New");
        emp.setAddress(addressNew);
        em.remove(address);
        // Map 1 to many
        dep.getEquipment().remove(equipment1.getId());
        Equipment equipment1New = new Equipment();
        equipment1New.setDescription("New_1");
        em.persist(equipment1New);
        dep.addEquipment(equipment1New);
        // additional change typically overrides existing aggregate or collection with the new one, then alters aggregate or adds to collection.
        if (addSecondStep) {
            // Aggregate
            emp.setPeriod(new EmploymentPeriod());
            emp.getPeriod().setStartDate(Helper.dateFromYearMonthDate(2001, 0, 1));
            emp.getPeriod().setEndDate(Helper.dateFromYearMonthDate(2003, 0, 1));
            // Aggregate
            emp.setFormerEmployment(new FormerEmployment("New_New", new EmploymentPeriod(Helper.dateFromYearMonthDate(1988, 0, 1), Helper.dateFromYearMonthDate(1991, 11, 31))));
            emp.getFormerEmployment().setPeriod(new EmploymentPeriod());
            emp.getFormerEmployment().getPeriod().setStartDate(Helper.dateFromYearMonthDate(1987, 0, 1));
            emp.getFormerEmployment().getPeriod().setEndDate(Helper.dateFromYearMonthDate(1990, 0, 1));
            // Transformation
            emp.setEndTime(Helper.timeFromHourMinuteSecond(18, 0, 0));
            // DirectCollection
            emp.setResponsibilities(new ArrayList());
            emp.addResponsibility("New_New_1");
            // Private Collection 1 to many
            emp.setPhoneNumbers(new HashSet());
            PhoneNumber phone1NewNew = new PhoneNumber("New_New_1", "111", "1111111");
            emp.addPhoneNumber(phone1NewNew);
            // Collection 1 to many
            emp1New.setManager(null);
            emp2.setManager(null);
            emp.setManagedEmployees(new Vector());
            Employee emp1NewNew = new Employee();
            emp1NewNew.setFirstName("TestChangeRecordKeepOldValue");
            emp1NewNew.setLastName("New_New_1");
            emp1NewNew.addProject(proj3);
            emp.addManagedEmployee(emp1NewNew);
            em.remove(emp1New);
            em.remove(emp2);
            // Collection many to many
            emp.setProjects(new ArrayList());
            Project proj1NewNew = new LargeProject();
            proj1NewNew.setName("New_New_1");
            emp.addProject(proj1NewNew);
            em.remove(proj1New);
            em.remove(proj2);
            // ObjectReference
            Address addressNewNew = new Address();
            addressNewNew.setCountry("New_New");
            addressNewNew.setProvince("New_New");
            addressNewNew.setCity("New_New");
            addressNewNew.setStreet("New_New");
            addressNewNew.setPostalCode("New_New");
            emp.setAddress(addressNewNew);
            em.remove(addressNew);
            // Map 1 to many
            // We are about to override equipment map.
            // It's a private OneToMany mapping so normally all the
            // members would be removed automatically.
            // However in theis case we have explicitly persisted the the new member added in thhe current transaction
            // (because Equipment's id is used as its key in the Department.equipment Map)
            // therefore we have to explicitly em.remove it.
            em.remove(equipment1New);
            dep.setEquipment(new HashMap());
            Equipment equipment1NewNew = new Equipment();
            equipment1NewNew.setDescription("New_New_1");
            em.persist(equipment1NewNew);
            dep.addEquipment(equipment1NewNew);
        }
        commitTransaction(em);
        // backup updated objects
        CopyGroup copyGroupUpdated = new CopyGroup();
        copyGroupUpdated.cascadeAllParts();
        dbs.copy(emp, copyGroupUpdated);
        // copies of the updated objects will be altered to contain old values.
        // if altering the test, make sure that emp still references (directly or through other objects) all the updated objects, so that all of them are copied.
        Map oldValueMap = copyGroupUpdated.getCopies();
        // using ChangeRecords bring back the original state of the object
        Iterator<Map.Entry<Object, org.eclipse.persistence.internal.sessions.ObjectChangeSet>> itChangeSets = ((org.eclipse.persistence.internal.sessions.UnitOfWorkChangeSet) listener.uowChangeSet).getCloneToObjectChangeSet().entrySet().iterator();
        while (itChangeSets.hasNext()) {
            Map.Entry<Object, org.eclipse.persistence.internal.sessions.ObjectChangeSet> entry = itChangeSets.next();
            Object object = entry.getKey();
            ClassDescriptor descriptor = dbs.getDescriptor(object);
            if (!descriptor.isAggregateDescriptor()) {
                org.eclipse.persistence.internal.sessions.ObjectChangeSet changeSet = entry.getValue();
                if (!changeSet.shouldBeDeleted() && !changeSet.isNew()) {
                    List<ChangeRecord> changes = changeSet.getChanges();
                    if (changes != null && !changes.isEmpty()) {
                        Object oldValueObject = oldValueMap.get(object);
                        for (ChangeRecord changeRecord : changeSet.getChanges()) {
                            Object oldValue = changeRecord.getOldValue();
                            DatabaseMapping mapping = ((org.eclipse.persistence.internal.sessions.ChangeRecord) changeRecord).getMapping();
                            mapping.setRealAttributeValueInObject(oldValueObject, oldValue);
                        }
                    }
                }
            }
        }
        String errorMsgOldValues = "";
        // now compare oldValue objects with corresponding backup objects
        itChangeSets = ((org.eclipse.persistence.internal.sessions.UnitOfWorkChangeSet) listener.uowChangeSet).getCloneToObjectChangeSet().entrySet().iterator();
        while (itChangeSets.hasNext()) {
            Map.Entry<Object, org.eclipse.persistence.internal.sessions.ObjectChangeSet> entry = itChangeSets.next();
            Object object = entry.getKey();
            ClassDescriptor descriptor = dbs.getDescriptor(object);
            if (!descriptor.isAggregateDescriptor()) {
                ObjectChangeSet changeSet = entry.getValue();
                if (!changeSet.shouldBeDeleted() && !changeSet.isNew()) {
                    List<ChangeRecord> changes = changeSet.getChanges();
                    if (changes != null && !changes.isEmpty()) {
                        Object oldValueObject = oldValueMap.get(object);
                        Object backupObject = backupMap.get(object);
                        // compare oldValue with backup object
                        if (!dbs.compareObjects(oldValueObject, backupObject)) {
                            errorMsgOldValues += '\t' + object.toString() + '\n';
                        }
                    }
                }
            }
        }
        // set of attached to em objects
        Set updatedObjects = new HashSet();
        for (Object object : oldValueMap.keySet()) {
            ClassDescriptor descriptor = dbs.getDescriptor(object);
            if (!descriptor.isAggregateDescriptor()) {
                updatedObjects.add(object);
            }
        }
        // verify that the objects were correctly written to the db
        String errorMsgDb = "";
        clearCache();
        Map updatedToReadBack = new HashMap();
        EntityManager em2 = createEntityManager();
        beginTransaction(em2);
        UnitOfWork uow2 = ((EntityManagerImpl) em2.getDelegate()).getActivePersistenceContext(null);
        // before comparison clear all read-only mappings that we didn't set in the attached to em objects.
        for (Object object : updatedObjects) {
            Object readBack = uow2.readObject(object);
            if (readBack instanceof Address) {
                ((Address) readBack).getEmployees().clear();
            } else if (readBack instanceof PhoneNumber) {
                ((PhoneNumber) readBack).setId(null);
            } else if (readBack instanceof Department) {
                ((Department) readBack).getEmployees().clear();
            }
            updatedToReadBack.put(object, readBack);
        }
        // now compare object attached to em with the object read from the db
        for (Object entryObject : updatedToReadBack.entrySet()) {
            Map.Entry entry = (Map.Entry) entryObject;
            Object object = entry.getKey();
            Object readBack = entry.getValue();
            if (!dbs.compareObjects(object, readBack)) {
                errorMsgDb += '\t' + object.toString() + '\n';
            }
        }
        rollbackTransaction(em2);
        // clean up
        beginTransaction(em);
        Set objectsToRemove = new HashSet();
        // remove all dependencies and add cache objects to be directly removed.
        for (Object object : updatedObjects) {
            if (object instanceof Employee) {
                ((Employee) object).getManagedEmployees().clear();
                ((Employee) object).setManager(null);
                ((Employee) object).setAddress((Address) null);
                ((Employee) object).getProjects().clear();
                ((Employee) object).setDepartment(null);
                objectsToRemove.add(object);
            } else if (object instanceof Project) {
                ((Project) object).setTeamLeader(null);
                objectsToRemove.add(object);
            } else if (object instanceof Address || object instanceof Department) {
                objectsToRemove.add(object);
            }
        }
        // remove objects that should be removed directly.
        for (Object object : objectsToRemove) {
            em.remove(object);
        }
        commitTransaction(em);
        String errorMsg = "";
        if (errorMsgOldValues.length() > 0) {
            errorMsgOldValues = "Some old values and back up objects are not equal:\n" + errorMsgOldValues;
            errorMsg += errorMsgOldValues;
        }
        if (errorMsgDb.length() > 0) {
            errorMsgDb = "\nSome values were incorrectly written into the db:\n" + errorMsgDb;
            errorMsg += errorMsgDb;
        }
        if (errorMsg.length() > 0) {
            fail(errorMsg);
        }
    } finally {
        if (isTransactionActive(em)) {
            rollbackTransaction(em);
        }
        closeEntityManager(em);
        dbs.getEventManager().removeListener(listener);
    }
}
Also used : SmallProject(org.eclipse.persistence.testing.models.jpa.composite.advanced.member_3.SmallProject) UnitOfWork(org.eclipse.persistence.sessions.UnitOfWork) RepeatableWriteUnitOfWork(org.eclipse.persistence.internal.sessions.RepeatableWriteUnitOfWork) ObjectChangeSet(org.eclipse.persistence.internal.sessions.ObjectChangeSet) Set(java.util.Set) HashSet(java.util.HashSet) UnitOfWorkChangeSet(org.eclipse.persistence.sessions.changesets.UnitOfWorkChangeSet) Address(org.eclipse.persistence.testing.models.jpa.composite.advanced.member_1.Address) ClassDescriptor(org.eclipse.persistence.descriptors.ClassDescriptor) HashMap(java.util.HashMap) EntityManagerImpl(org.eclipse.persistence.internal.jpa.EntityManagerImpl) FormerEmployment(org.eclipse.persistence.testing.models.jpa.composite.advanced.member_2.FormerEmployment) UnitOfWorkChangeSet(org.eclipse.persistence.sessions.changesets.UnitOfWorkChangeSet) ArrayList(java.util.ArrayList) Department(org.eclipse.persistence.testing.models.jpa.composite.advanced.member_1.Department) ObjectChangeSet(org.eclipse.persistence.internal.sessions.ObjectChangeSet) Vector(java.util.Vector) HashSet(java.util.HashSet) EmploymentPeriod(org.eclipse.persistence.testing.models.jpa.composite.advanced.member_2.EmploymentPeriod) ObjectChangeSet(org.eclipse.persistence.internal.sessions.ObjectChangeSet) DatabaseMapping(org.eclipse.persistence.mappings.DatabaseMapping) LargeProject(org.eclipse.persistence.testing.models.jpa.composite.advanced.member_3.LargeProject) SuperLargeProject(org.eclipse.persistence.testing.models.jpa.composite.advanced.member_3.SuperLargeProject) Project(org.eclipse.persistence.testing.models.jpa.composite.advanced.member_3.Project) SmallProject(org.eclipse.persistence.testing.models.jpa.composite.advanced.member_3.SmallProject) EntityManager(jakarta.persistence.EntityManager) JpaEntityManager(org.eclipse.persistence.jpa.JpaEntityManager) Employee(org.eclipse.persistence.testing.models.jpa.composite.advanced.member_2.Employee) Equipment(org.eclipse.persistence.testing.models.jpa.composite.advanced.member_3.Equipment) DatabaseSessionImpl(org.eclipse.persistence.internal.sessions.DatabaseSessionImpl) CopyGroup(org.eclipse.persistence.sessions.CopyGroup) PhoneNumber(org.eclipse.persistence.testing.models.jpa.composite.advanced.member_3.PhoneNumber) Map(java.util.Map) HashMap(java.util.HashMap) ChangeRecord(org.eclipse.persistence.sessions.changesets.ChangeRecord) LargeProject(org.eclipse.persistence.testing.models.jpa.composite.advanced.member_3.LargeProject) SuperLargeProject(org.eclipse.persistence.testing.models.jpa.composite.advanced.member_3.SuperLargeProject)

Example 3 with EntityManagerImpl

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

the class EntityManagerJUnitTestSuite method internalTestChangeRecordKeepOldValue.

public void internalTestChangeRecordKeepOldValue(boolean addSecondStep) {
    if (isOnServer()) {
        // the test relies upon keeping attached objects between transactions.
        return;
    }
    // but these are transient for remote sessions.
    if (getDatabaseSession().isRemoteSession()) {
        return;
    }
    AbstractSession session = getDatabaseSession();
    ChangeRecordKeepOldValueListener listener = new ChangeRecordKeepOldValueListener();
    session.getEventManager().addListener(listener);
    EntityManager em = createEntityManager();
    try {
        // setup
        // create original object and referenced objects
        Employee emp = new Employee();
        emp.setFirstName("TestChangeRecordKeepOldValue");
        emp.setLastName("Manager_OriginalName");
        emp.setMale();
        emp.setSalary(35000);
        emp.setPeriod(new EmploymentPeriod(Helper.dateFromYearMonthDate(1993, 0, 1), Helper.dateFromYearMonthDate(1996, 11, 31)));
        emp.setFormerEmployment(new FormerEmployment("Original", new EmploymentPeriod(Helper.dateFromYearMonthDate(1990, 0, 1), Helper.dateFromYearMonthDate(1993, 11, 31))));
        Address address = new Address();
        address.setCountry("Original");
        address.setProvince("Original");
        address.setCity("Original");
        address.setStreet("Original");
        address.setPostalCode("Original");
        emp.setAddress(address);
        Department dep = new Department();
        dep.setName("Original");
        emp.setDepartment(dep);
        emp.addResponsibility("Original_1");
        emp.addResponsibility("Original_2");
        PhoneNumber phone1 = new PhoneNumber("Original_1", "111", "1111111");
        emp.addPhoneNumber(phone1);
        PhoneNumber phone2 = new PhoneNumber("Original_2", "222", "2222222");
        emp.addPhoneNumber(phone2);
        Employee emp1 = new Employee();
        emp1.setFirstName("TestChangeRecordKeepOldValue");
        emp1.setLastName("Original_1");
        emp.addManagedEmployee(emp1);
        Employee emp2 = new Employee();
        emp2.setFirstName("TestChangeRecordKeepOldValue");
        emp2.setLastName("Original_2");
        emp.addManagedEmployee(emp2);
        Project proj1 = new SmallProject();
        proj1.setName("Original_1");
        emp.addProject(proj1);
        Project proj2 = new LargeProject();
        proj2.setName("Original_2");
        emp.addProject(proj2);
        Project proj3 = new LargeProject();
        proj3.setName("Original_3");
        proj3.setTeamLeader(emp);
        emp1.addProject(proj3);
        emp2.addProject(proj3);
        // persist original object and all referenced objects
        beginTransaction(em);
        Equipment equipment1 = new Equipment();
        equipment1.setDescription("Original_1");
        // persist is not cascaded for department.equipment - have to explicitly persist it.
        em.persist(equipment1);
        dep.addEquipment(equipment1);
        Equipment equipment2 = new Equipment();
        equipment2.setDescription("Original_2");
        // persist is not cascaded for department.equipment - have to explicitly persist it.
        // moreover, equipment.id is used as a key in dep.equipment Map, therefore equipmet
        // should be persisted before been added to dep.
        em.persist(equipment2);
        dep.addEquipment(equipment2);
        // persist is not cascaded for employee.department - have to explicitly persist it.
        // moreover, equipment.id is used as a key in dep.equipment Map, therefore equipmet
        // should be persisted before been added to dep.
        em.persist(dep);
        em.persist(emp);
        commitTransaction(em);
        // backup original object and all referenced objects
        CopyGroup copyGroupBackup = new CopyGroup();
        copyGroupBackup.cascadeAllParts();
        session.copy(emp, copyGroupBackup);
        // emp references (directly or through other objects) all the created objects, therefore all of them are copied.
        Map backupMap = copyGroupBackup.getCopies();
        // verify that backup objects are identical to originals
        Iterator<Map.Entry> it = backupMap.entrySet().iterator();
        while (it.hasNext()) {
            Map.Entry entry = it.next();
            Object original = entry.getKey();
            ClassDescriptor descriptor = session.getDescriptor(original);
            if (!descriptor.isAggregateDescriptor()) {
                Object backup = entry.getValue();
                if (original == backup) {
                    fail("Test problem: backup failed: original == backup: " + original);
                }
                if (!session.compareObjects(original, backup)) {
                    fail("Test problem: backup failed: compareObjects(original, backup) == false: " + original + "; " + backup);
                }
            }
        }
        Set deleted = new HashSet();
        // change original object
        beginTransaction(em);
        // DirectToField
        emp.setLastName("Manager_NewName");
        // DirectToField
        emp.setSalary(100);
        // Aggregate
        emp.getPeriod().setStartDate(Helper.dateFromYearMonthDate(2000, 0, 1));
        emp.getPeriod().setEndDate(Helper.dateFromYearMonthDate(2002, 0, 1));
        // Aggregate
        // emp.setFormerEmployment(new FormerEmployment("New", new EmploymentPeriod(Helper.dateFromYearMonthDate(1989, 0, 1), Helper.dateFromYearMonthDate(1992, 11, 31))));
        emp.getFormerEmployment().setFormerCompany("New");
        emp.getFormerEmployment().getPeriod().setStartDate(Helper.dateFromYearMonthDate(1989, 0, 1));
        emp.getFormerEmployment().getPeriod().setStartDate(Helper.dateFromYearMonthDate(1992, 11, 31));
        // **temp for debug
        FormerEmployment fe = emp.getFormerEmployment();
        // DirectCollection
        emp.removeResponsibility("Original_1");
        emp.addResponsibility("New_1");
        // Private Collection 1 to many
        PhoneNumber phone1New = new PhoneNumber("New_1", "111", "1111111");
        emp.addPhoneNumber(phone1New);
        emp.removePhoneNumber(phone1);
        // Collection 1 to many
        emp.removeManagedEmployee(emp1);
        emp1.setManager(null);
        em.remove(emp1);
        deleted.add(emp1);
        Employee emp1New = new Employee();
        emp1New.setFirstName("TestChangeRecordKeepOldValue");
        emp1New.setLastName("New_1");
        emp1New.addProject(proj3);
        emp.addManagedEmployee(emp1New);
        // Collection many to many
        emp.removeProject(proj1);
        em.remove(proj1);
        deleted.add(proj1);
        Project proj1New = new LargeProject();
        proj1New.setName("New_1");
        emp.addProject(proj1New);
        // ObjectReference
        proj3.setTeamLeader(null);
        // ObjectReference
        Address addressNew = new Address();
        addressNew.setCountry("New");
        addressNew.setProvince("New");
        addressNew.setCity("New");
        addressNew.setStreet("New");
        addressNew.setPostalCode("New");
        emp.setAddress(addressNew);
        em.remove(address);
        deleted.add(address);
        // Map 1 to many
        dep.getEquipment().remove(equipment1.getId());
        Equipment equipment1New = new Equipment();
        equipment1New.setDescription("New_1");
        em.persist(equipment1New);
        dep.addEquipment(equipment1New);
        // additional change typically overrides existing aggregate or collection with the new one, then alters aggregate or adds to collection.
        // **temp for debug
        FormerEmployment fe2 = null;
        if (addSecondStep) {
            // Aggregate
            emp.setPeriod(new EmploymentPeriod());
            emp.getPeriod().setStartDate(Helper.dateFromYearMonthDate(2001, 0, 1));
            emp.getPeriod().setEndDate(Helper.dateFromYearMonthDate(2003, 0, 1));
            // Aggregate
            // **temp for debug
            fe2 = emp.getFormerEmployment();
            emp.setFormerEmployment(new FormerEmployment("New_New", new EmploymentPeriod(Helper.dateFromYearMonthDate(1988, 0, 1), Helper.dateFromYearMonthDate(1991, 11, 31))));
            /*                emp.getFormerEmployment().setPeriod(new EmploymentPeriod());
                emp.getFormerEmployment().getPeriod().setStartDate(Helper.dateFromYearMonthDate(1987, 0, 1));
                emp.getFormerEmployment().getPeriod().setEndDate(Helper.dateFromYearMonthDate(1990, 0, 1));*/
            // DirectCollection
            emp.setResponsibilities(new ArrayList());
            emp.addResponsibility("New_New_1");
            // Private Collection 1 to many
            emp.setPhoneNumbers(new HashSet());
            PhoneNumber phone1NewNew = new PhoneNumber("New_New_1", "111", "1111111");
            emp.addPhoneNumber(phone1NewNew);
            // Collection 1 to many
            emp1New.setManager(null);
            emp2.setManager(null);
            emp.setManagedEmployees(new Vector());
            Employee emp1NewNew = new Employee();
            emp1NewNew.setFirstName("TestChangeRecordKeepOldValue");
            emp1NewNew.setLastName("New_New_1");
            emp1NewNew.addProject(proj3);
            emp.addManagedEmployee(emp1NewNew);
            em.remove(emp1New);
            em.remove(emp2);
            deleted.add(emp1New);
            deleted.add(emp2);
            // Collection many to many
            emp.setProjects(new ArrayList());
            Project proj1NewNew = new LargeProject();
            proj1NewNew.setName("New_New_1");
            emp.addProject(proj1NewNew);
            em.remove(proj1New);
            em.remove(proj2);
            deleted.add(proj1New);
            deleted.add(proj2);
            // ObjectReference
            Address addressNewNew = new Address();
            addressNewNew.setCountry("New_New");
            addressNewNew.setProvince("New_New");
            addressNewNew.setCity("New_New");
            addressNewNew.setStreet("New_New");
            addressNewNew.setPostalCode("New_New");
            emp.setAddress(addressNewNew);
            em.remove(addressNew);
            deleted.add(addressNew);
            // Map 1 to many
            // We are about to override equipment map.
            // It's a private OneToMany mapping so normally all the
            // members would be removed automatically.
            // However in this case we have explicitly persisted the the new member added in thhe current transaction
            // (because Equipment's id is used as its key in the Department.equipment Map)
            // therefore we have to explicitly em.remove it.
            em.remove(equipment1New);
            deleted.add(equipment1New);
            dep.setEquipment(new HashMap());
            Equipment equipment1NewNew = new Equipment();
            equipment1NewNew.setDescription("New_New_1");
            em.persist(equipment1NewNew);
            dep.addEquipment(equipment1NewNew);
        }
        commitTransaction(em);
        // backup updated objects
        CopyGroup copyGroupUpdated = new CopyGroup();
        copyGroupUpdated.cascadeAllParts();
        session.copy(emp, copyGroupUpdated);
        // copies of the updated objects will be altered to contain old values.
        // if altering the test, make sure that emp still references (directly or through other objects) all the updated objects, so that all of them are copied.
        Map oldValueMap = copyGroupUpdated.getCopies();
        // using ChangeRecords bring back the original state of the object
        Iterator<Map.Entry<Object, org.eclipse.persistence.internal.sessions.ObjectChangeSet>> itChangeSets = ((org.eclipse.persistence.internal.sessions.UnitOfWorkChangeSet) listener.uowChangeSet).getCloneToObjectChangeSet().entrySet().iterator();
        while (itChangeSets.hasNext()) {
            Map.Entry<Object, org.eclipse.persistence.internal.sessions.ObjectChangeSet> entry = itChangeSets.next();
            Object object = entry.getKey();
            ClassDescriptor descriptor = session.getDescriptor(object);
            if (!descriptor.isAggregateDescriptor()) {
                ObjectChangeSet changeSet = entry.getValue();
                if (!(deleted.contains(object)) && !changeSet.isNew()) {
                    List<ChangeRecord> changes = changeSet.getChanges();
                    if (changes != null && !changes.isEmpty()) {
                        Object oldValueObject = oldValueMap.get(object);
                        if (oldValueObject != null) {
                            for (ChangeRecord changeRecord : changeSet.getChanges()) {
                                Object oldValue = changeRecord.getOldValue();
                                DatabaseMapping mapping = ((org.eclipse.persistence.internal.sessions.ChangeRecord) changeRecord).getMapping();
                                mapping.setRealAttributeValueInObject(oldValueObject, oldValue);
                            }
                        }
                    }
                }
            }
        }
        String errorMsgOldValues = "";
        // now compare oldValue objects with corresponding backup objects
        itChangeSets = ((org.eclipse.persistence.internal.sessions.UnitOfWorkChangeSet) listener.uowChangeSet).getCloneToObjectChangeSet().entrySet().iterator();
        while (itChangeSets.hasNext()) {
            Map.Entry<Object, org.eclipse.persistence.internal.sessions.ObjectChangeSet> entry = itChangeSets.next();
            Object object = entry.getKey();
            ClassDescriptor descriptor = session.getDescriptor(object);
            if (!descriptor.isAggregateDescriptor()) {
                ObjectChangeSet changeSet = entry.getValue();
                if (!(deleted.contains(object)) && !changeSet.isNew()) {
                    List<ChangeRecord> changes = changeSet.getChanges();
                    if (changes != null && !changes.isEmpty()) {
                        Object oldValueObject = oldValueMap.get(object);
                        Object backupObject = backupMap.get(object);
                        // compare oldValue with backup object
                        if ((oldValueObject != null) && !session.compareObjects(oldValueObject, backupObject)) {
                            errorMsgOldValues += '\t' + object.toString() + '\n';
                        }
                    }
                }
            }
        }
        // set of attached to em objects
        Set updatedObjects = new HashSet();
        for (Object object : oldValueMap.keySet()) {
            ClassDescriptor descriptor = session.getDescriptor(object);
            if (!descriptor.isAggregateDescriptor()) {
                updatedObjects.add(object);
            }
        }
        // verify that the objects were correctly written to the db
        String errorMsgDb = "";
        clearCache();
        Map updatedToReadBack = new HashMap();
        EntityManager em2 = createEntityManager();
        beginTransaction(em2);
        UnitOfWork uow2 = ((EntityManagerImpl) em2.getDelegate()).getActivePersistenceContext(null);
        // before comparison clear all read-only mappings that we didn't set in the attached to em objects.
        for (Object object : updatedObjects) {
            Object readBack = uow2.readObject(object);
            if (readBack instanceof Project) {
                ((Project) readBack).getTeamMembers().clear();
            } else if (readBack instanceof Address) {
                ((Address) readBack).getEmployees().clear();
            } else if (readBack instanceof Department) {
                ((Department) readBack).getEmployees().clear();
            }
            updatedToReadBack.put(object, readBack);
        }
        // now compare object attached to em with the object read from the db
        for (Object entryObject : updatedToReadBack.entrySet()) {
            Map.Entry entry = (Map.Entry) entryObject;
            Object object = entry.getKey();
            Object readBack = entry.getValue();
            if (!session.compareObjects(object, readBack)) {
                errorMsgDb += '\t' + object.toString() + '\n';
            }
        }
        rollbackTransaction(em2);
        // clean up
        beginTransaction(em);
        Set objectsToRemove = new HashSet();
        // remove all dependencies and add cache objects to be directly removed.
        for (Object object : updatedObjects) {
            if (object instanceof Employee) {
                ((Employee) object).getManagedEmployees().clear();
                ((Employee) object).setManager(null);
                ((Employee) object).setAddress(null);
                ((Employee) object).getProjects().clear();
                ((Employee) object).setDepartment(null);
                objectsToRemove.add(object);
            } else if (object instanceof Project) {
                ((Project) object).setTeamLeader(null);
                objectsToRemove.add(object);
            } else if (object instanceof Address || object instanceof Department) {
                objectsToRemove.add(object);
            }
        }
        // remove objects that should be removed directly.
        for (Object object : objectsToRemove) {
            em.remove(object);
        }
        commitTransaction(em);
        String errorMsg = "";
        if (errorMsgOldValues.length() > 0) {
            errorMsgOldValues = "Some old values and back up objects are not equal:\n" + errorMsgOldValues;
            errorMsg += errorMsgOldValues;
        }
        if (errorMsgDb.length() > 0) {
            errorMsgDb = "\nSome values were incorrectly written into the db:\n" + errorMsgDb;
            errorMsg += errorMsgDb;
        }
        if (errorMsg.length() > 0) {
            fail(errorMsg);
        }
    } finally {
        if (isTransactionActive(em)) {
            rollbackTransaction(em);
        }
        closeEntityManager(em);
        session.getEventManager().removeListener(listener);
    }
}
Also used : SmallProject(org.eclipse.persistence.testing.models.jpa.fieldaccess.advanced.SmallProject) UnitOfWork(org.eclipse.persistence.sessions.UnitOfWork) Set(java.util.Set) ObjectChangeSet(org.eclipse.persistence.sessions.changesets.ObjectChangeSet) HashSet(java.util.HashSet) UnitOfWorkChangeSet(org.eclipse.persistence.sessions.changesets.UnitOfWorkChangeSet) Address(org.eclipse.persistence.testing.models.jpa.fieldaccess.advanced.Address) ClassDescriptor(org.eclipse.persistence.descriptors.ClassDescriptor) HashMap(java.util.HashMap) EntityManagerImpl(org.eclipse.persistence.internal.jpa.EntityManagerImpl) FormerEmployment(org.eclipse.persistence.testing.models.jpa.fieldaccess.advanced.FormerEmployment) UnitOfWorkChangeSet(org.eclipse.persistence.sessions.changesets.UnitOfWorkChangeSet) ArrayList(java.util.ArrayList) Department(org.eclipse.persistence.testing.models.jpa.fieldaccess.advanced.Department) SessionLogEntry(org.eclipse.persistence.logging.SessionLogEntry) Vector(java.util.Vector) AbstractSession(org.eclipse.persistence.internal.sessions.AbstractSession) HashSet(java.util.HashSet) EmploymentPeriod(org.eclipse.persistence.testing.models.jpa.fieldaccess.advanced.EmploymentPeriod) ObjectChangeSet(org.eclipse.persistence.sessions.changesets.ObjectChangeSet) DatabaseMapping(org.eclipse.persistence.mappings.DatabaseMapping) LargeProject(org.eclipse.persistence.testing.models.jpa.fieldaccess.advanced.LargeProject) SuperLargeProject(org.eclipse.persistence.testing.models.jpa.fieldaccess.advanced.SuperLargeProject) SmallProject(org.eclipse.persistence.testing.models.jpa.fieldaccess.advanced.SmallProject) Project(org.eclipse.persistence.testing.models.jpa.fieldaccess.advanced.Project) EntityManager(jakarta.persistence.EntityManager) JpaEntityManager(org.eclipse.persistence.jpa.JpaEntityManager) Employee(org.eclipse.persistence.testing.models.jpa.fieldaccess.advanced.Employee) Equipment(org.eclipse.persistence.testing.models.jpa.fieldaccess.advanced.Equipment) CopyGroup(org.eclipse.persistence.sessions.CopyGroup) PhoneNumber(org.eclipse.persistence.testing.models.jpa.fieldaccess.advanced.PhoneNumber) Map(java.util.Map) NoIdentityMap(org.eclipse.persistence.testing.models.jpa.fieldaccess.advanced.NoIdentityMap) HashMap(java.util.HashMap) ChangeRecord(org.eclipse.persistence.sessions.changesets.ChangeRecord) LargeProject(org.eclipse.persistence.testing.models.jpa.fieldaccess.advanced.LargeProject) SuperLargeProject(org.eclipse.persistence.testing.models.jpa.fieldaccess.advanced.SuperLargeProject)

Example 4 with EntityManagerImpl

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

the class RelationshipModelJUnitTestSuite method testGetResultListTest.

/*
     * Tests using the 'getSingleResult' api on a Query object obtained from the
     * EntityManager Also tests bugs 4300879 - check non Collection container
     * policy error and 4297903 - check ReadObjectQuery fails
     */
public void testGetResultListTest() {
    Collection returnedCustomers1, returnedCustomers2;
    QueryException expectedException1 = null;
    String ejbql1 = "SELECT OBJECT(thecust) FROM Customer thecust WHERE thecust.customerId = :id";
    Integer[] cusIDs = new Integer[3];
    Customer cusClone1 = RelationshipsExamples.customerExample1();
    Customer cusClone2 = RelationshipsExamples.customerExample2();
    EntityManager em = createEntityManager();
    beginTransaction(em);
    em.persist(cusClone1);
    em.persist(cusClone2);
    commitTransaction(em);
    em.clear();
    clearCache();
    cusIDs[0] = cusClone1.getCustomerId();
    cusIDs[1] = cusClone2.getCustomerId();
    try {
        beginTransaction(em);
        EntityManagerImpl entityManagerImpl = (EntityManagerImpl) em.getDelegate();
        Query query1 = em.createNamedQuery("findAllCustomers");
        returnedCustomers1 = query1.getResultList();
        Query query2 = em.createQuery(ejbql1);
        query2.setParameter("id", -10);
        returnedCustomers2 = query2.getResultList();
        // bug:4297903, check container policy failure
        EJBQueryImpl query3 = (EJBQueryImpl) entityManagerImpl.createQuery(ejbql1);
        ReadAllQuery readAllQuery = new ReadAllQuery(Customer.class);
        MapContainerPolicy mapContainerPolicy = new MapContainerPolicy();
        mapContainerPolicy.setContainerClass(HashMap.class);
        mapContainerPolicy.setKeyName("hashCode");
        readAllQuery.setContainerPolicy(mapContainerPolicy);
        query3.setDatabaseQuery(readAllQuery);
        try {
            query3.getResultList();
        } catch (PersistenceException exc) {
            // QueryException.INVALID_CONTAINER_CLASS
            expectedException1 = (QueryException) exc.getCause();
            rollbackTransaction(em);
            beginTransaction(em);
        }
        entityManagerImpl = (EntityManagerImpl) em.getDelegate();
        // bug:4300879, check ReadObjectQuery fails
        EJBQueryImpl query4 = (EJBQueryImpl) entityManagerImpl.createQuery(ejbql1);
        query4.setParameter("id", -10);
        ReadObjectQuery readObjectQuery2 = new ReadObjectQuery(Customer.class);
        readObjectQuery2.setEJBQLString(ejbql1);
        query4.setDatabaseQuery(readObjectQuery2);
        query4.getResultList();
        commitTransaction(em);
        if (returnedCustomers1 == null || (returnedCustomers1.size() < 2)) {
            fail("Not all customers were returned from findAllCustomers query ");
        }
        if (returnedCustomers2 == null || (returnedCustomers2.size() != 0)) {
            fail("Customer from ReadObjectQuery was not returned using getResultCollection");
        }
        if (expectedException1 == null || (expectedException1.getErrorCode() != QueryException.INVALID_CONTAINER_CLASS)) {
            fail("getResultCollection on query returning a hashtable did not throw expected INVALID_CONTAINER_CLASS QueryException");
        }
        beginTransaction(em);
        Customer cus1 = em.find(Customer.class, cusIDs[0]);
        em.remove(cus1);
        Customer cus2 = em.find(Customer.class, cusIDs[1]);
        em.remove(cus2);
        commitTransaction(em);
    } finally {
        if (isTransactionActive(em)) {
            rollbackTransaction(em);
        }
    }
}
Also used : Query(jakarta.persistence.Query) ReadAllQuery(org.eclipse.persistence.queries.ReadAllQuery) ReadObjectQuery(org.eclipse.persistence.queries.ReadObjectQuery) ReadObjectQuery(org.eclipse.persistence.queries.ReadObjectQuery) Customer(org.eclipse.persistence.testing.models.jpa.relationships.Customer) EntityManagerImpl(org.eclipse.persistence.internal.jpa.EntityManagerImpl) MapContainerPolicy(org.eclipse.persistence.internal.queries.MapContainerPolicy) ReadAllQuery(org.eclipse.persistence.queries.ReadAllQuery) EJBQueryImpl(org.eclipse.persistence.internal.jpa.EJBQueryImpl) QueryException(org.eclipse.persistence.exceptions.QueryException) EntityManager(jakarta.persistence.EntityManager) PersistenceException(jakarta.persistence.PersistenceException) CustomerCollection(org.eclipse.persistence.testing.models.jpa.relationships.CustomerCollection) Collection(java.util.Collection)

Example 5 with EntityManagerImpl

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

the class RelationshipModelJUnitTestSuite method testChangeSetForNewObject.

// Bug 357103
public void testChangeSetForNewObject() {
    EntityManager em = createEntityManager();
    beginTransaction(em);
    Customer cust = new Customer();
    cust.setName("Joe");
    em.persist(cust);
    Order order = new Order();
    order.setQuantity(1);
    em.persist(order);
    cust.addOrder(order);
    commitTransaction(em);
    RepeatableWriteUnitOfWork uow = null;
    try {
        beginTransaction(em);
        cust = em.find(Customer.class, cust.getCustomerId());
        Order order2 = new Order();
        order2.setQuantity(2);
        order2.setShippingAddress("123 Main St.");
        em.persist(order2);
        cust.addOrder(order2);
        EntityManagerImpl impl = (EntityManagerImpl) JpaHelper.getEntityManager(em);
        uow = impl.getActivePersistenceContext(null);
        em.flush();
        UnitOfWorkChangeSet uowChangeSet = uow.getCumulativeUOWChangeSet();
        ObjectChangeSet customerChangeSet = uowChangeSet.getCloneToObjectChangeSet().get(cust);
        CollectionChangeRecord orderChangeRecord = (CollectionChangeRecord) customerChangeSet.getChangesForAttributeNamed("orders");
        Iterator<ObjectChangeSet> i = orderChangeRecord.getAddObjectList().keySet().iterator();
        while (i.hasNext()) {
            ObjectChangeSet orderChangeSet = i.next();
            assertTrue("There are changes in the change set.  There should be no changes for a new object.", orderChangeSet.getChanges().isEmpty());
        }
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        rollbackTransaction(em);
        beginTransaction(em);
        cust = em.find(Customer.class, cust.getCustomerId());
        em.remove(cust);
        commitTransaction(em);
    }
}
Also used : Order(org.eclipse.persistence.testing.models.jpa.relationships.Order) EntityManager(jakarta.persistence.EntityManager) Customer(org.eclipse.persistence.testing.models.jpa.relationships.Customer) EntityManagerImpl(org.eclipse.persistence.internal.jpa.EntityManagerImpl) UnitOfWorkChangeSet(org.eclipse.persistence.internal.sessions.UnitOfWorkChangeSet) ObjectChangeSet(org.eclipse.persistence.internal.sessions.ObjectChangeSet) RepeatableWriteUnitOfWork(org.eclipse.persistence.internal.sessions.RepeatableWriteUnitOfWork) CollectionChangeRecord(org.eclipse.persistence.internal.sessions.CollectionChangeRecord) PersistenceException(jakarta.persistence.PersistenceException) QueryException(org.eclipse.persistence.exceptions.QueryException) NonUniqueResultException(jakarta.persistence.NonUniqueResultException) NoResultException(jakarta.persistence.NoResultException)

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