Search in sources :

Example 46 with OneToManyMapping

use of org.eclipse.persistence.mappings.OneToManyMapping in project eclipselink by eclipse-ee4j.

the class AdvancedJPAJunitTest method testTransparentIndirectionQuerySessionReset.

/**
 * Bug 489898 - RepeatableWriteUnitOfWork linked by QueryBasedValueHolder in shared cache in specific scenario
 *
 * Complex scenario: In a transaction, associate an existing object to a new object, refresh the existing object.
 * In a second transaction, read the new object and traverse relationships to the existing object, and trigger
 * an indirect relationship. The existing wrapped indirection query on the indirect relationship should
 * ensure that the UnitOfWork (RepeatableWriteUnitOfWork) used for the query is unreferenced correctly, to
 * avoid referencing it within the shared cache, via the existing referenced query.
 */
public void testTransparentIndirectionQuerySessionReset() {
    Bill bill = null;
    BillLine billLine = null;
    BillLineItem billLineItem = null;
    BillAction billAction = null;
    // setup
    EntityManager em = createEntityManager();
    try {
        beginTransaction(em);
        bill = new Bill();
        bill.setOrderIdentifier("Test Bill");
        billLine = new BillLine();
        billLine.setQuantity(6);
        bill.addBillLine(billLine);
        billLineItem = new BillLineItem();
        billLineItem.setItemName("Test Widget");
        billLine.addBillLineItem(billLineItem);
        em.persist(bill);
        em.persist(billLine);
        em.persist(billLineItem);
        commitTransaction(em);
        assertNotNull("bill should be non-null", bill);
        assertNotNull("bill's id should be non-null", bill.getId());
        assertNotNull("billLine should be non-null", billLine);
        assertNotNull("billLine's id should be non-null", billLine.getId());
        assertNotNull("billLineItem should be non-null", billLineItem);
        assertNotNull("billLineItem's id should be non-null", billLineItem.getId());
    } finally {
        closeEntityManager(em);
        // start test with an empty cache
        clearCache();
    }
    try {
        // test - txn #1 : read, modify, persist, refresh related Entity
        em = createEntityManager();
        try {
            beginTransaction(em);
            Bill billReRead = em.createQuery("SELECT b FROM Bill b where b.id=" + bill.getId(), Bill.class).getSingleResult();
            assertNotNull(billReRead);
            BillLine billLineReRead = billReRead.getBillLines().get(0);
            assertNotNull(billLineReRead);
            billAction = new BillAction();
            billAction.setBillLine(billLineReRead);
            billAction.setPriority(2);
            em.persist(billAction);
            // refresh
            em.refresh(billLineReRead);
            commitTransaction(em);
        } finally {
            if (isTransactionActive(em)) {
                rollbackTransaction(em);
            }
            closeEntityManager(em);
        }
        // test - txn #2 : read, modify and trigger relationship on related Entity
        em = createEntityManager();
        try {
            beginTransaction(em);
            Bill billReRead = em.createQuery("SELECT b FROM Bill b where b.id=" + bill.getId(), Bill.class).getSingleResult();
            // DM: if there is no update to Order, issue doesn't occur
            billReRead.setStatus(Bill.STATUS_PROCESSING);
            BillAction billActionReRead = em.createQuery("SELECT a FROM BillAction a where a.id=" + billAction.getId(), BillAction.class).getSingleResult();
            assertNotNull(billActionReRead);
            BillLine billLineReRead = billActionReRead.getBillLine();
            assertNotNull(billLineReRead);
            // Access & trigger BillLine -> BillLineItems list
            billLineReRead.getBillLineItems().size();
            commitTransaction(em);
        } finally {
            if (isTransactionActive(em)) {
                rollbackTransaction(em);
            }
            closeEntityManager(em);
        }
        // verify
        // Failure case: non-null session (a UnitOfWork/RepeatableWriteUnitOfWork) referenced in the wrapped ValueHolder's query.
        ServerSession srv = getServerSession();
        ClassDescriptor descriptor = srv.getDescriptor(billLine);
        Long blId = billLine.getId();
        BillLine cachedBillLine = (BillLine) srv.getIdentityMapAccessor().getFromIdentityMap(blId, BillLine.class);
        assertNotNull("BillLine from shared cache is null with id: " + blId, cachedBillLine);
        OneToManyMapping mapping = (OneToManyMapping) srv.getDescriptor(cachedBillLine).getMappingForAttributeName("billLineItems");
        IndirectContainer billLineItemsVH = (IndirectContainer) mapping.getAttributeValueFromObject(cachedBillLine);
        assertNotNull("BillLineItems ValueHolder should not be null", billLineItemsVH);
        ValueHolderInterface wrappedVH = billLineItemsVH.getValueHolder();
        assertNotNull("Wrapped ValueHolder should not be null", wrappedVH);
        if (wrappedVH instanceof QueryBasedValueHolder) {
            DatabaseQuery query = ((QueryBasedValueHolder) wrappedVH).getQuery();
            if (query.getSession() != null && query.getSession().isUnitOfWork()) {
                fail("UnitOfWork referenced in Query from wrapped QueryBasedValueHolder in shared cache");
            }
        }
    } finally {
        // reset
        em = createEntityManager();
        try {
            beginTransaction(em);
            bill = em.find(Bill.class, bill.getId());
            if (bill != null) {
                em.remove(bill);
            }
            billLine = em.find(BillLine.class, billLine.getId());
            if (billLine != null) {
                em.remove(billLine);
            }
            billLineItem = em.find(BillLineItem.class, billLineItem.getId());
            if (billLineItem != null) {
                em.remove(billLineItem);
            }
            if (billAction != null) {
                billAction = em.find(BillAction.class, billAction.getId());
                if (billAction != null) {
                    em.remove(billAction);
                }
            }
            commitTransaction(em);
        } finally {
            closeEntityManager(em);
        }
    }
}
Also used : ServerSession(org.eclipse.persistence.sessions.server.ServerSession) ClassDescriptor(org.eclipse.persistence.descriptors.ClassDescriptor) DatabaseQuery(org.eclipse.persistence.queries.DatabaseQuery) BillLine(org.eclipse.persistence.testing.models.jpa.advanced.BillLine) UnidirectionalOneToManyMapping(org.eclipse.persistence.mappings.UnidirectionalOneToManyMapping) OneToManyMapping(org.eclipse.persistence.mappings.OneToManyMapping) BillAction(org.eclipse.persistence.testing.models.jpa.advanced.BillAction) BillLineItem(org.eclipse.persistence.testing.models.jpa.advanced.BillLineItem) QueryBasedValueHolder(org.eclipse.persistence.internal.indirection.QueryBasedValueHolder) EntityManager(jakarta.persistence.EntityManager) JpaEntityManager(org.eclipse.persistence.jpa.JpaEntityManager) ValueHolderInterface(org.eclipse.persistence.indirection.ValueHolderInterface) IndirectContainer(org.eclipse.persistence.indirection.IndirectContainer) Bill(org.eclipse.persistence.testing.models.jpa.advanced.Bill)

Example 47 with OneToManyMapping

use of org.eclipse.persistence.mappings.OneToManyMapping in project eclipselink by eclipse-ee4j.

the class MappingConfigTestSuite method verifyEmployeeDescriptor.

@Test
public void verifyEmployeeDescriptor() throws Exception {
    ClassDescriptor descriptor = serverSession.getDescriptorForAlias("Employee");
    assertNotNull(descriptor);
    assertEquals("Employee", descriptor.getAlias());
    assertNull(descriptor.getInheritancePolicyOrNull());
    // Address Mapping
    OneToOneMapping addrMapping = (OneToOneMapping) descriptor.getMappingForAttributeName("address");
    assertNotNull(addrMapping);
    assertTrue(addrMapping.isPrivateOwned());
    assertSame(serverSession.getDescriptorForAlias("Address"), addrMapping.getReferenceDescriptor());
    // PhoneNumber Mapping
    OneToManyMapping phoneMapping = (OneToManyMapping) descriptor.getMappingForAttributeName("phoneNumbers");
    assertNotNull(phoneMapping);
    assertTrue(phoneMapping.isPrivateOwned());
    assertSame(serverSession.getDescriptorForAlias("PhoneNumber"), phoneMapping.getReferenceDescriptor());
    // Manager Mapping
    OneToOneMapping managerMapping = (OneToOneMapping) descriptor.getMappingForAttributeName("manager");
    assertNotNull(managerMapping);
    assertFalse(managerMapping.isPrivateOwned());
    assertSame(descriptor, managerMapping.getReferenceDescriptor());
    // Managed Employees Mapping
    OneToManyMapping managedEmployeesMapping = (OneToManyMapping) descriptor.getMappingForAttributeName("managedEmployees");
    assertNotNull(managedEmployeesMapping);
    assertFalse(managedEmployeesMapping.isPrivateOwned());
    assertSame(descriptor, managedEmployeesMapping.getReferenceDescriptor());
    // Projects Mapping
    ManyToManyMapping projectsMapping = (ManyToManyMapping) descriptor.getMappingForAttributeName("projects");
    assertNotNull(projectsMapping);
    assertFalse(projectsMapping.isPrivateOwned());
    assertSame(serverSession.getDescriptorForAlias("Project"), projectsMapping.getReferenceDescriptor());
}
Also used : ManyToManyMapping(org.eclipse.persistence.mappings.ManyToManyMapping) ClassDescriptor(org.eclipse.persistence.descriptors.ClassDescriptor) OneToManyMapping(org.eclipse.persistence.mappings.OneToManyMapping) OneToOneMapping(org.eclipse.persistence.mappings.OneToOneMapping) Test(org.junit.Test)

Example 48 with OneToManyMapping

use of org.eclipse.persistence.mappings.OneToManyMapping in project eclipselink by eclipse-ee4j.

the class DynamicEmployeeSystem method configureEmployee.

private static void configureEmployee(JPADynamicTypeBuilder employee, JPADynamicTypeBuilder address, JPADynamicTypeBuilder phone, JPADynamicTypeBuilder period, JPADynamicTypeBuilder project) {
    employee.setPrimaryKeyFields("EMP_ID");
    employee.addDirectMapping("id", int.class, "D_EMPLOYEE.EMP_ID");
    employee.addDirectMapping("firstName", String.class, "D_EMPLOYEE.F_NAME");
    employee.addDirectMapping("lastName", String.class, "D_EMPLOYEE.L_NAME");
    employee.addDirectMapping("gender", String.class, "D_EMPLOYEE.GENDER");
    employee.addDirectMapping("salary", int.class, "D_SALARY.SALARY");
    OneToOneMapping addressMapping = employee.addOneToOneMapping("address", address.getType(), "ADDR_ID");
    addressMapping.setCascadeAll(true);
    addressMapping.setIsPrivateOwned(true);
    employee.addOneToOneMapping("manager", employee.getType(), "MANAGER_ID");
    OneToManyMapping phoneMapping = employee.addOneToManyMapping("phoneNumbers", phone.getType(), "EMP_ID");
    phoneMapping.setCascadeAll(true);
    phoneMapping.setIsPrivateOwned(true);
    employee.addAggregateObjectMapping("period", period.getType(), true);
    employee.addOneToManyMapping("managedEmployees", employee.getType(), "MANAGER_ID");
    employee.configureSequencing("EMP_SEQ", "EMP_ID");
}
Also used : OneToManyMapping(org.eclipse.persistence.mappings.OneToManyMapping) OneToOneMapping(org.eclipse.persistence.mappings.OneToOneMapping)

Example 49 with OneToManyMapping

use of org.eclipse.persistence.mappings.OneToManyMapping in project eclipselink by eclipse-ee4j.

the class ForeignKeyTestSuite method testMapKeyForeignKey.

/**
 * Tests a map key foreign key setting.
 */
public void testMapKeyForeignKey() {
    ClassDescriptor runnerDescriptor = getPersistenceUnitServerSession().getDescriptor(Runner.class);
    OneToManyMapping mapping = (OneToManyMapping) runnerDescriptor.getMappingForAttributeName("shoes");
    OneToOneMapping keyMapping = (OneToOneMapping) ((MappedKeyMapContainerPolicy) mapping.getContainerPolicy()).getKeyMapping();
    DatabaseTable table = keyMapping.getForeignKeyFields().get(0).getTable();
    assertForeignKeyConstraint("Runner_ShoeTag_Foreign_Key", "FOREIGN KEY (TAG_ID) REFERENCES JPA22_DDL_SHOE_TAG (ID)", table);
}
Also used : ClassDescriptor(org.eclipse.persistence.descriptors.ClassDescriptor) OneToManyMapping(org.eclipse.persistence.mappings.OneToManyMapping) DatabaseTable(org.eclipse.persistence.internal.helper.DatabaseTable) OneToOneMapping(org.eclipse.persistence.mappings.OneToOneMapping)

Example 50 with OneToManyMapping

use of org.eclipse.persistence.mappings.OneToManyMapping in project eclipselink by eclipse-ee4j.

the class OneToManyAccessor method processOneToManyMapping.

/**
 * INTERNAL:
 * Process an one to many mapping for this accessor.
 */
protected void processOneToManyMapping() {
    // Non-owning side, process the foreign keys from the owner.
    DatabaseMapping owningMapping = getOwningMapping();
    if (owningMapping.isOneToOneMapping()) {
        OneToOneMapping ownerMapping = (OneToOneMapping) owningMapping;
        // If the owner uses a relation table mechanism we must map a M-M.
        if (ownerMapping.hasRelationTableMechanism()) {
            ManyToManyMapping mapping = new ManyToManyMapping();
            // Process the common collection mapping.
            process(mapping);
            // Process the mapped by relation table metadata.
            processMappedByRelationTable(ownerMapping.getRelationTableMechanism(), mapping.getRelationTableMechanism());
            // Set the mapping to read only
            mapping.setIsReadOnly(true);
            mapping.setMappedBy(getMappedBy());
        } else {
            // Create a 1-M mapping and process common collection mapping
            // metadata first followed by specific metadata.
            OneToManyMapping mapping = new OneToManyMapping();
            process(mapping);
            Map<DatabaseField, DatabaseField> keys = ownerMapping.getSourceToTargetKeyFields();
            for (DatabaseField fkField : keys.keySet()) {
                DatabaseField pkField = keys.get(fkField);
                // point and can avoid the cloning)
                if (getDescriptor().usesTablePerClassInheritanceStrategy() && !pkField.getTable().equals(getDescriptor().getPrimaryTable())) {
                    // We need to update the pk field to be to our table.
                    pkField = pkField.clone();
                    pkField.setTable(getDescriptor().getPrimaryTable());
                }
                mapping.addTargetForeignKeyField(fkField, pkField);
            }
            mapping.setMappedBy(getMappedBy());
        }
    } else {
        // If improper mapping encountered, throw an exception.
        throw ValidationException.invalidMapping(getJavaClass(), getReferenceClass());
    }
}
Also used : ManyToManyMapping(org.eclipse.persistence.mappings.ManyToManyMapping) UnidirectionalOneToManyMapping(org.eclipse.persistence.mappings.UnidirectionalOneToManyMapping) EISOneToManyMapping(org.eclipse.persistence.eis.mappings.EISOneToManyMapping) OneToManyMapping(org.eclipse.persistence.mappings.OneToManyMapping) DatabaseField(org.eclipse.persistence.internal.helper.DatabaseField) DatabaseMapping(org.eclipse.persistence.mappings.DatabaseMapping) OneToOneMapping(org.eclipse.persistence.mappings.OneToOneMapping)

Aggregations

OneToManyMapping (org.eclipse.persistence.mappings.OneToManyMapping)50 RelationalDescriptor (org.eclipse.persistence.descriptors.RelationalDescriptor)18 DirectToFieldMapping (org.eclipse.persistence.mappings.DirectToFieldMapping)18 OneToOneMapping (org.eclipse.persistence.mappings.OneToOneMapping)16 ClassDescriptor (org.eclipse.persistence.descriptors.ClassDescriptor)13 Expression (org.eclipse.persistence.expressions.Expression)6 TransparentIndirectionPolicy (org.eclipse.persistence.internal.indirection.TransparentIndirectionPolicy)6 DatabaseMapping (org.eclipse.persistence.mappings.DatabaseMapping)6 UnidirectionalOneToManyMapping (org.eclipse.persistence.mappings.UnidirectionalOneToManyMapping)6 Test (org.junit.Test)6 ExpressionBuilder (org.eclipse.persistence.expressions.ExpressionBuilder)5 DatabaseField (org.eclipse.persistence.internal.helper.DatabaseField)5 TransformationMapping (org.eclipse.persistence.mappings.TransformationMapping)5 DynamicType (org.eclipse.persistence.dynamic.DynamicType)4 DatabaseTable (org.eclipse.persistence.internal.helper.DatabaseTable)4 ManyToManyMapping (org.eclipse.persistence.mappings.ManyToManyMapping)4 EntityManager (jakarta.persistence.EntityManager)3 ArrayList (java.util.ArrayList)3 List (java.util.List)3 EclipseLinkException (org.eclipse.persistence.exceptions.EclipseLinkException)3