org.eclipse.persistence.mappings.OneToOneMapping Java Examples

The following examples show how to use org.eclipse.persistence.mappings.OneToOneMapping. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: JoinCriteriaMappingProcessor.java    From cuba with Apache License 2.0 6 votes vote down vote up
@Override
public void process(MappingProcessorContext context) {
    DatabaseMapping mapping = context.getMapping();

    Expression expression = AppBeans.getAll(JoinExpressionProvider.class)
            .values().stream()
            .map(provider -> provider.getJoinCriteriaExpression(mapping))
            .filter(Objects::nonNull)
            .reduce(Expression::and).orElse(null);

    //Applying additional join criteria, e.g. for soft delete or multitenancy -> move to mapping processor
    if (mapping.isOneToManyMapping() || mapping.isOneToOneMapping()) {
        //Apply expression to mappings
        if (mapping.isOneToManyMapping()) {
            ((OneToManyMapping) mapping).setAdditionalJoinCriteria(expression);
        } else if (mapping.isOneToOneMapping()) {
            ((OneToOneMapping) mapping).setAdditionalJoinCriteria(expression);
        }
    }
}
 
Example #2
Source File: SoftDeleteMappingProcessor.java    From cuba with Apache License 2.0 6 votes vote down vote up
@Override
public void process(MappingProcessorContext context) {
    DatabaseMapping mapping = context.getMapping();
    ClassDescriptor descriptor = mapping.getDescriptor();
    Field referenceField =  FieldUtils.getAllFieldsList(descriptor.getJavaClass())
            .stream().filter(f -> f.getName().equals(mapping.getAttributeName())).findFirst().orElse(null);

    if (mapping.isOneToOneMapping()) {
        OneToOneMapping oneToOneMapping = (OneToOneMapping) mapping;
        if (SoftDelete.class.isAssignableFrom(oneToOneMapping.getReferenceClass())) {
            if (mapping.isManyToOneMapping()) {
                oneToOneMapping.setSoftDeletionForBatch(false);
                oneToOneMapping.setSoftDeletionForValueHolder(false);
            } else if (referenceField != null) {
                OneToOne oneToOne = referenceField.getAnnotation(OneToOne.class);
                if (oneToOne != null) {
                    if (Strings.isNullOrEmpty(oneToOne.mappedBy())) {
                        oneToOneMapping.setSoftDeletionForBatch(false);
                        oneToOneMapping.setSoftDeletionForValueHolder(false);
                    }
                }
            }
        }
    }

}
 
Example #3
Source File: UuidMappingProcessor.java    From cuba with Apache License 2.0 6 votes vote down vote up
@Override
public void process(MappingProcessorContext context) {
    DatabaseMapping mapping = context.getMapping();
    Session session = context.getSession();

    MetaClass metaClass = metadata.getSession().getClassNN(mapping.getDescriptor().getJavaClass());

    String attributeName = mapping.getAttributeName();
    MetaProperty metaProperty = metaClass.getPropertyNN(attributeName);
    if (metaProperty.getRange().isDatatype()) {
        if (metaProperty.getJavaType().equals(UUID.class)) {
            ((DirectToFieldMapping) mapping).setConverter(UuidConverter.getInstance());
            setDatabaseFieldParameters(session, mapping.getField());
        }
    } else if (metaProperty.getRange().isClass() && !metaProperty.getRange().getCardinality().isMany()) {
        MetaClass refMetaClass = metaProperty.getRange().asClass();
        MetaProperty refPkProperty = metadata.getTools().getPrimaryKeyProperty(refMetaClass);
        if (refPkProperty != null && refPkProperty.getJavaType().equals(UUID.class)) {
            for (DatabaseField field : ((OneToOneMapping) mapping).getForeignKeyFields()) {
                setDatabaseFieldParameters(session, field);
            }
        }
    }

}
 
Example #4
Source File: EclipseLinkJpaMetadataProviderImpl.java    From rice with Educational Community License v2.0 6 votes vote down vote up
/**
 * Gets the inverse extension of the given {@link ClassDescriptor}.
 *
 * @param extensionEntityDescriptor the {@link ClassDescriptor} of which to get the inverse.
 * @param entityType the type of the entity.
 * @return the inverse extension of the given {@link ClassDescriptor}.
 */
protected OneToOneMapping findExtensionInverse(ClassDescriptor extensionEntityDescriptor, Class<?> entityType) {
    Collection<DatabaseMapping> derivedIdMappings = extensionEntityDescriptor.getDerivesIdMappinps();
    String extensionInfo = "(" + extensionEntityDescriptor.getJavaClass().getName() + " -> " + entityType.getName()
            + ")";
    if (derivedIdMappings == null || derivedIdMappings.isEmpty()) {
        throw new MetadataConfigurationException("Attempting to use extension framework, but extension "
                + extensionInfo + " does not have a valid inverse OneToOne Id mapping back to the extended data "
                + "object. Please ensure it is annotated property for use of the extension framework with JPA.");
    } else if (derivedIdMappings.size() > 1) {
        throw new MetadataConfigurationException("When attempting to determine the inverse relationship for use "
                + "with extension framework " + extensionInfo + " encountered more than one 'derived id' mapping, "
                + "there should be only one!");
    }
    DatabaseMapping inverseMapping = derivedIdMappings.iterator().next();
    if (!(inverseMapping instanceof OneToOneMapping)) {
        throw new MetadataConfigurationException("Identified an inverse derived id mapping for extension "
                + "relationship " + extensionInfo + " but it was not a one-to-one mapping: " + inverseMapping);
    }
    return (OneToOneMapping)inverseMapping;
}
 
Example #5
Source File: SoftDeleteJoinExpressionProvider.java    From cuba with Apache License 2.0 5 votes vote down vote up
@Override
protected Expression processOneToOneMapping(OneToOneMapping mapping) {
    ClassDescriptor descriptor = mapping.getDescriptor();
    Field referenceField = FieldUtils.getAllFieldsList(descriptor.getJavaClass())
            .stream().filter(f -> f.getName().equals(mapping.getAttributeName()))
            .findFirst().orElse(null);
    if (SoftDelete.class.isAssignableFrom(mapping.getReferenceClass()) && referenceField != null) {
        OneToOne oneToOne = referenceField.getAnnotation(OneToOne.class);
        if (oneToOne != null && !Strings.isNullOrEmpty(oneToOne.mappedBy())) {
            return new ExpressionBuilder().get("deleteTs").isNull();
        }
    }
    return null;
}
 
Example #6
Source File: AbstractJoinExpressionProvider.java    From cuba with Apache License 2.0 5 votes vote down vote up
@Override
public Expression getJoinCriteriaExpression(DatabaseMapping mapping) {
    if (mapping.isOneToManyMapping()) {
        return processOneToManyMapping((OneToManyMapping)mapping);
    } else if (mapping.isOneToOneMapping()) {
        if (mapping.isManyToOneMapping()) {
            return processManyToOneMapping((ManyToOneMapping) mapping);
        } else {
            return processOneToOneMapping((OneToOneMapping) mapping);
        }
    } else if (mapping.isManyToManyMapping()) {
        return processManyToManyMapping((ManyToManyMapping) mapping);
    }
    return null;
}
 
Example #7
Source File: JPAMDefaultTableGenerator.java    From jeddict with Apache License 2.0 5 votes vote down vote up
protected void addForeignKeyFieldToSourceTargetTable(ManagedClass managedClass, Attribute managedAttribute, LinkedList<Entity> intrinsicEntity, LinkedList<Attribute> intrinsicAttribute, boolean isInherited, OneToOneMapping mapping) {
    if (!mapping.isForeignKeyRelationship()
            || (mapping.getReferenceDescriptor().hasTablePerClassPolicy()
            && mapping.getReferenceDescriptor().getTablePerClassPolicy().hasChild())) {
        return;
    }
    boolean cascadeDelete = false;
    // Find mappedBy target mapping to check constraint cascade.
    for (DatabaseField foreignKey : mapping.getSourceToTargetKeyFields().values()) {
        DatabaseMapping mappedBy = mapping.getReferenceDescriptor().getObjectBuilder().getMappingForField(foreignKey);
        if (mappedBy != null && mappedBy.isOneToOneMapping()) {
            cascadeDelete = ((OneToOneMapping) mappedBy).isCascadeOnDeleteSetOnDatabase();
        } else {
            List<DatabaseMapping> readOnlyMappings = mapping.getReferenceDescriptor().getObjectBuilder().getReadOnlyMappingsForField(foreignKey);
            if (readOnlyMappings != null) {
                for (DatabaseMapping mappedByPK : readOnlyMappings) {
                    if (mappedByPK.isOneToOneMapping()) {
                        cascadeDelete = ((OneToOneMapping) mappedByPK).isCascadeOnDeleteSetOnDatabase();
                        if (cascadeDelete) {
                            break;
                        }
                    }
                }
            }
        }
        if (cascadeDelete) {
            break;
        }
    }

    // If the mapping is optional and uses primary key join columns, don't
    // generate foreign key constraints which would require the target to
    // always be set.
    if (!mapping.isOptional() || !mapping.isOneToOnePrimaryKeyRelationship()) {
        addForeignMappingFkConstraint(managedClass, managedAttribute, intrinsicEntity, intrinsicAttribute, isInherited, mapping.getSourceToTargetKeyFields(), cascadeDelete);
    }
}
 
Example #8
Source File: EclipseLinkAnnotationMetadataProviderImplTest.java    From rice with Educational Community License v2.0 5 votes vote down vote up
@Test
public void testExtensionAttribute_eclipselink_data() {
	ClassDescriptor classDescriptor = jpaMetadataProvider.getClassDescriptor(TestDataObject.class);
	ClassDescriptor referenceDescriptor = jpaMetadataProvider.getClassDescriptor(TestDataObjectExtension.class);
	assertNotNull("A classDescriptor should have been retrieved from JPA for TestDataObject", classDescriptor);
	assertNotNull("A classDescriptor should have been retrieved from JPA for TestDataObjectExtension",
               referenceDescriptor);
	DatabaseMapping databaseMapping = classDescriptor.getMappingForAttributeName("extension");
       assertNotNull("extension mapping missing from metamodel", databaseMapping);
       assertTrue("Should be a OneToOne mapping", databaseMapping instanceof OneToOneMapping);
       OneToOneMapping mapping = (OneToOneMapping)databaseMapping;

       assertEquals("Should be mapped by primaryKeyProperty", "primaryKeyProperty", mapping.getMappedBy());
       Map<DatabaseField, DatabaseField> databaseFields = mapping.getSourceToTargetKeyFields();
       assertEquals(1, databaseFields.size());
       for (DatabaseField sourceField : databaseFields.keySet()) {
           DatabaseField targetField = databaseFields.get(sourceField);
           assertEquals("PK_PROP", sourceField.getName());
           assertEquals("PK_PROP", targetField.getName());
       }

	assertNotNull("Reference descriptor missing from relationship", mapping.getReferenceDescriptor());
	assertEquals("Reference descriptor should be the one for TestDataObjectExtension", referenceDescriptor,
               mapping.getReferenceDescriptor());

	assertNotNull("selection query relationship missing", mapping.getSelectionQuery());
	assertNotNull("selection query missing name", mapping.getSelectionQuery().getName());
	assertEquals("selection query name incorrect", "extension", mapping.getSelectionQuery().getName());
	assertNotNull("selection query reference class", mapping.getSelectionQuery().getReferenceClass());
	assertEquals("selection query reference class incorrect", TestDataObjectExtension.class,
               mapping.getSelectionQuery().getReferenceClass());
	assertNotNull("selection query reference class name", mapping.getSelectionQuery().getReferenceClassName());
	assertNotNull("selection query source mapping missing", mapping.getSelectionQuery().getSourceMapping());
	assertEquals("selection query source mapping incorrect", mapping,
               mapping.getSelectionQuery().getSourceMapping());
}
 
Example #9
Source File: JPAMDefaultTableGenerator.java    From jeddict with Apache License 2.0 4 votes vote down vote up
/**
     *
     * @param baseDescriptor
     * @param intrinsicEntity defines the Entity Object that contains embedded
     * Object where Entity object will be intrinsicEntity and Embeddable object
     * will be descriptorManagedClass
     * @param intrinsicAttribute
     */
    protected void postInitTableSchema(ClassDescriptor baseDescriptor, LinkedList<Entity> intrinsicEntity, LinkedList<Attribute> intrinsicAttribute) {

        DBRelationalDescriptor descriptor = (DBRelationalDescriptor) baseDescriptor;
        ManagedClass descriptorManagedClass = null;

        if (intrinsicEntity == null) {
            if (descriptor.getAccessor() instanceof EntitySpecAccessor) {
                intrinsicEntity = new LinkedList<>();
                intrinsicAttribute = new LinkedList<>();
                intrinsicEntity.offer(((EntitySpecAccessor) descriptor.getAccessor()).getEntity());
                descriptorManagedClass = intrinsicEntity.peek();
            } else {
                throw new IllegalStateException(descriptor.getAccessor() + " not supported");
            }
        } else if (descriptor.getAccessor() instanceof EmbeddableSpecAccessor) {
            descriptorManagedClass = ((EmbeddableSpecAccessor) descriptor.getAccessor()).getEmbeddable();
        }  else if (descriptor.getAccessor() instanceof DefaultClassSpecAccessor) {
//            descriptorManagedClass = ((DefaultClassSpecAccessor) descriptor.getAccessor()).getDefaultClass();
        } else {
            throw new IllegalStateException(descriptor.getAccessor() + " not supported");
        }

        for (DatabaseMapping mapping : descriptor.getMappings()) {
            ManagedClass managedClass = descriptorManagedClass;
            Attribute managedAttribute = (Attribute) mapping.getProperty(Attribute.class);
            Boolean isInherited = (Boolean) mapping.getProperty(Inheritance.class);
            isInherited = isInherited == null ? false : isInherited;
            
            if (intrinsicAttribute.peek() == null) {
                intrinsicAttribute.offer(managedAttribute);
            }

           if(managedAttribute instanceof RelationAttribute && !((RelationAttribute)managedAttribute).isOwner()){
               //skip non-owner
           } else if (descriptor.isChildDescriptor() && descriptor.getInheritancePolicy().getParentDescriptor().getMappingForAttributeName(mapping.getAttributeName()) != null) {
                // If we are an inheritance subclass, do nothing. That is, don't
                // generate mappings that will be generated by our parent,
                // otherwise the fields for that mapping will be generated n
                // times for the same table.
            } else if (mapping.isManyToManyMapping()) {
                buildRelationTableDefinition(managedClass, managedAttribute, intrinsicEntity, intrinsicAttribute, isInherited, (ManyToManyMapping) mapping, ((ManyToManyMapping) mapping).getRelationTableMechanism(), ((ManyToManyMapping) mapping).getListOrderField(), mapping.getContainerPolicy());
            } else if (mapping.isDirectCollectionMapping()) {
                buildDirectCollectionTableDefinition(managedClass, managedAttribute, intrinsicEntity, intrinsicAttribute, isInherited, (DirectCollectionMapping) mapping, descriptor);
            } else if (mapping.isDirectToFieldMapping()) {
                Converter converter = ((DirectToFieldMapping) mapping).getConverter();
                if (converter != null) {
                    if (converter instanceof TypeConversionConverter) {
                        resetFieldTypeForLOB((DirectToFieldMapping) mapping);
                    }

                    // uncomment on upgrade to eclipselink v2.7.2+
//                    if (converter instanceof SerializedObjectConverter) {
//                        //serialized object mapping field should be BLOB/IMAGE
//                        getFieldDefFromDBField(mapping.getField()).setType(((SerializedObjectConverter) converter).getSerializer().getType());
//                    }
                }
            } else if (mapping.isAggregateCollectionMapping()) {
                //need to figure out the target foreign key field and add it into the aggregate target table
//               if(managedAttribute instanceof ElementCollection || ((ElementCollection)managedAttribute).getConnectedClass()!=null){
//                   ClassDescriptor refDescriptor = mapping.getReferenceDescriptor();
//                                    Attribute attribute = getManagedAttribute(refDescriptor, dbField, intrinsicAttribute);//TODO intrinsicAttribute nested path/attribute not set
//
//               }
                createAggregateTargetTable(managedClass, managedAttribute, intrinsicEntity, intrinsicAttribute, isInherited, (AggregateCollectionMapping) mapping);
            } else if (mapping.isForeignReferenceMapping()) {
                if (mapping.isOneToOneMapping()) {
                    RelationTableMechanism relationTableMechanism = ((OneToOneMapping) mapping).getRelationTableMechanism();
                    if (relationTableMechanism == null) {
                        addForeignKeyFieldToSourceTargetTable(managedClass, managedAttribute, intrinsicEntity, intrinsicAttribute, isInherited, (OneToOneMapping) mapping);
                    } else {
                        buildRelationTableDefinition(managedClass, managedAttribute, intrinsicEntity, intrinsicAttribute, isInherited, (OneToOneMapping) mapping, relationTableMechanism, null, null);
                    }
                } else if (mapping.isOneToManyMapping()) {
                    addForeignKeyFieldToSourceTargetTable(managedClass, managedAttribute, intrinsicEntity, intrinsicAttribute, isInherited, (OneToManyMapping) mapping);
                    TableDefinition targTblDef = getTableDefFromDBTable(((OneToManyMapping) mapping).getReferenceDescriptor().getDefaultTable());//TODO pass entity
                    addFieldsForMappedKeyMapContainerPolicy(managedClass, managedAttribute, intrinsicEntity, intrinsicAttribute, isInherited, mapping.getContainerPolicy(), targTblDef);
                }
            } else if (mapping.isTransformationMapping()) {
                resetTransformedFieldType((TransformationMapping) mapping);
            } else if (mapping.isAggregateObjectMapping()) {
                postInitTableSchema(((AggregateObjectMapping) mapping).getReferenceDescriptor(), new LinkedList<>(intrinsicEntity), new LinkedList<>(intrinsicAttribute));
            }
            intrinsicAttribute.clear();
        }

        processAdditionalTablePkFields(intrinsicEntity, descriptor);
        intrinsicEntity.clear();

    }
 
Example #10
Source File: EclipseLinkJpaMetadataProviderImpl.java    From rice with Educational Community License v2.0 4 votes vote down vote up
/**
    * {@inheritDoc}
    */
@Override
protected void populateImplementationSpecificRelationshipLevelMetadata(DataObjectRelationshipImpl relationship,
		SingularAttribute<?, ?> rd) {
	// We need to go into the repository and grab the table name.
	Class<?> referencedClass = rd.getBindableJavaType();
	EntityType<?> referencedEntityType = entityManager.getMetamodel().entity(referencedClass);
	if (referencedEntityType instanceof EntityTypeImpl) {
		relationship
				.setBackingObjectName(((EntityTypeImpl<?>) referencedEntityType).getDescriptor().getTableName());
	}
	// Set to read only if store (save) operations should not be pushed through
	PersistentAttributeType persistentAttributeType = rd.getPersistentAttributeType();

	if (rd instanceof SingularAttributeImpl) {
		SingularAttributeImpl<?, ?> rel = (SingularAttributeImpl<?, ?>) rd;

		OneToOneMapping relationshipMapping = (OneToOneMapping) rel.getMapping();
		relationship.setReadOnly(relationshipMapping.isReadOnly());
		relationship.setSavedWithParent(relationshipMapping.isCascadePersist());
		relationship.setDeletedWithParent(relationshipMapping.isCascadeRemove());
		relationship.setLoadedAtParentLoadTime(relationshipMapping.isCascadeRefresh()
				&& !relationshipMapping.isLazy());
		relationship.setLoadedDynamicallyUponUse(relationshipMapping.isCascadeRefresh()
				&& relationshipMapping.isLazy());

           List<DataObjectAttributeRelationship> attributeRelationships = new ArrayList<DataObjectAttributeRelationship>();
           List<String> referencedEntityPkFields = getPrimaryKeyAttributeNames(referencedEntityType);

           for (String referencedEntityPkField : referencedEntityPkFields) {
               for (Map.Entry<DatabaseField, DatabaseField> entry :
                       relationshipMapping.getTargetToSourceKeyFields().entrySet()) {
                   DatabaseField childDatabaseField = entry.getKey();
                   String childFieldName = getPropertyNameFromDatabaseColumnName(referencedEntityType,
                           childDatabaseField.getName());

                   if (referencedEntityPkField.equalsIgnoreCase(childFieldName)) {
                       DatabaseField parentDatabaseField = entry.getValue();
                       String parentFieldName = getPropertyNameFromDatabaseColumnName(rd.getDeclaringType(),
                               parentDatabaseField.getName());

                       if (parentFieldName != null) {
                           attributeRelationships
                                   .add(new DataObjectAttributeRelationshipImpl(parentFieldName, childFieldName));
                           break;
                       } else {
                           LOG.warn("Unable to find parent field reference.  There may be a JPA mapping problem on " +
                                   referencedEntityType.getJavaType() + ": " + relationship);
                       }
                   }
               }
           }

           relationship.setAttributeRelationships(attributeRelationships);

           populateInverseRelationship(relationshipMapping, relationship);

	} else {
		// get what we can based on JPA values (note that we just set some to have values here)
		relationship.setReadOnly(persistentAttributeType == PersistentAttributeType.MANY_TO_ONE);
		relationship.setSavedWithParent(persistentAttributeType == PersistentAttributeType.ONE_TO_ONE);
		relationship.setDeletedWithParent(persistentAttributeType == PersistentAttributeType.ONE_TO_ONE);
		relationship.setLoadedAtParentLoadTime(true);
		relationship.setLoadedDynamicallyUponUse(false);
	}
}
 
Example #11
Source File: EclipseLinkJpaMetadataProviderImpl.java    From rice with Educational Community License v2.0 4 votes vote down vote up
/**
    * {@inheritDoc}
    */
@Override
public DataObjectRelationship addExtensionRelationship(Class<?> entityClass, String extensionPropertyName,
		Class<?> extensionEntityClass) {
	ClassDescriptor entityDescriptor = getClassDescriptor(entityClass);
	ClassDescriptor extensionEntityDescriptor = getClassDescriptor(extensionEntityClass);

	if (LOG.isDebugEnabled()) {
		LOG.debug("About to attempt to inject a 1:1 relationship on PKs between " + entityDescriptor + " and "
				+ extensionEntityDescriptor);
	}
	OneToOneMapping dm = (OneToOneMapping) entityDescriptor.newOneToOneMapping();
	dm.setAttributeName(extensionPropertyName);
	dm.setReferenceClass(extensionEntityClass);
	dm.setDescriptor(entityDescriptor);
	dm.setIsPrivateOwned(true);
	dm.setJoinFetch(ForeignReferenceMapping.OUTER_JOIN);
	dm.setCascadeAll(true);
	dm.setIsLazy(false);
	dm.dontUseIndirection();
	dm.setIsOneToOneRelationship(true);
	dm.setRequiresTransientWeavedFields(false);

       OneToOneMapping inverse = findExtensionInverse(extensionEntityDescriptor, entityClass);
       dm.setMappedBy(inverse.getAttributeName());
       for (DatabaseField sourceField : inverse.getSourceToTargetKeyFields().keySet()) {
           DatabaseField targetField = inverse.getSourceToTargetKeyFields().get(sourceField);
           // reverse them, pass the source from the inverse as our target and the target from the inverse as our source
           dm.addTargetForeignKeyField(sourceField, targetField);
       }

       dm.preInitialize(getEclipseLinkEntityManager().getDatabaseSession());
	dm.initialize(getEclipseLinkEntityManager().getDatabaseSession());
	entityDescriptor.addMapping(dm);
	entityDescriptor.getObjectBuilder().initialize(getEclipseLinkEntityManager().getDatabaseSession());

       // build the data object relationship
       ManagedTypeImpl<?> managedType = (ManagedTypeImpl<?>)getEntityManager().getMetamodel().managedType(entityClass);
       SingularAttributeImpl<?, ?> singularAttribute = new SingularAttributeLocal(managedType, dm);
       return getRelationshipMetadata(singularAttribute);
}
 
Example #12
Source File: AbstractJoinExpressionProvider.java    From cuba with Apache License 2.0 votes vote down vote up
protected abstract Expression processOneToOneMapping(OneToOneMapping mapping);