org.eclipse.persistence.mappings.DatabaseMapping Java Examples

The following examples show how to use org.eclipse.persistence.mappings.DatabaseMapping. 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: JPAMDefaultTableGenerator.java    From jeddict with Apache License 2.0 6 votes vote down vote up
private Attribute getManagedAttribute(ClassDescriptor refDescriptor, DatabaseField dbField, LinkedList<Attribute> intrinsicAttribute) {
    if (refDescriptor != null) {
        for (DatabaseMapping refMapping : refDescriptor.getMappings()) {
            if(!refMapping.getFields()
                    .stream()
                    .filter(field -> field == dbField)
                    .findAny()
                    .isPresent()){
                continue;
            }
            
            if (refMapping.getFields().size() > 1) {
                intrinsicAttribute.add((Attribute) refMapping.getProperty(Attribute.class));
                if(refMapping.getReferenceDescriptor() == refDescriptor){ //self-relationship with composite pk
                    return (Attribute) refMapping.getProperty(Attribute.class);
                } else {
                    return getManagedAttribute(refMapping.getReferenceDescriptor(), dbField, intrinsicAttribute);
                }
            } else if (!refMapping.getFields().isEmpty() && refMapping.getFields().get(0) == dbField) {
                intrinsicAttribute.add((Attribute) refMapping.getProperty(Attribute.class));
                return (Attribute) refMapping.getProperty(Attribute.class);
            }
        }
    }
    return null;
}
 
Example #2
Source File: PrefixSessionCustomizer.java    From tomee with Apache License 2.0 6 votes vote down vote up
@Override
public void customize(final Session session) throws Exception {
    if (JPAThreadContext.infos.containsKey("properties")) {
        final String prefix = ((Properties) JPAThreadContext.infos.get("properties")).getProperty("openejb.jpa.table_prefix");
        final List<DatabaseTable> tables = new ArrayList<DatabaseTable>();
        for (final ClassDescriptor cd : session.getDescriptors().values()) {
            for (final DatabaseTable table : cd.getTables()) {
                update(prefix, tables, table);
            }
            for (final DatabaseMapping mapping : cd.getMappings()) {
                if (mapping instanceof ManyToManyMapping) {
                    update(prefix, tables, ((ManyToManyMapping) mapping).getRelationTable());
                } else if (mapping instanceof DirectCollectionMapping) {
                    update(prefix, tables, ((DirectCollectionMapping) mapping).getReferenceTable());
                } // TODO: else check we need to update something
            }
        }

        final Sequence sequence = session.getDatasourcePlatform().getDefaultSequence();
        if (sequence instanceof TableSequence) {
            final TableSequence ts = ((TableSequence) sequence);
            ts.setName(prefix + ts.getName());
        }
    }
}
 
Example #3
Source File: CamelNamingStrategy.java    From gazpachoquest with GNU General Public License v3.0 6 votes vote down vote up
@Override
public void customize(final Session session) throws SQLException {
    for (ClassDescriptor descriptor : session.getDescriptors().values()) {
        if (!descriptor.getTables().isEmpty()) {
            // Take table name from @Table if exists
            String tableName = null;
            if (descriptor.getAlias().equalsIgnoreCase(descriptor.getTableName())) {
                tableName = unqualify(descriptor.getJavaClassName());
            } else {
                tableName = descriptor.getTableName();
            }
            tableName = camelCaseToUnderscore(tableName);
            descriptor.setTableName(tableName);

            for (IndexDefinition index : descriptor.getTables().get(0).getIndexes()) {
                index.setTargetTable(tableName);
            }
            Vector<DatabaseMapping> mappings = descriptor.getMappings();
            camelCaseToUnderscore(mappings);
        } else if (descriptor.isAggregateDescriptor() || descriptor.isChildDescriptor()) {
            camelCaseToUnderscore(descriptor.getMappings());
        }
    }
}
 
Example #4
Source File: EclipseLinkAnnotationMetadataProviderImplTest.java    From rice with Educational Community License v2.0 6 votes vote down vote up
@Test
public void testConvertersEstabished_autoApply_Boolean() throws Exception {
	ClassDescriptor classDescriptor = jpaMetadataProvider.getClassDescriptor(TestDataObject.class);
	DatabaseMapping attribute = classDescriptor.getMappingForAttributeName("booleanProperty");
	assertEquals("attribute data type mismatch", DirectToFieldMapping.class, attribute.getClass());
	Converter converter = ((org.eclipse.persistence.mappings.DirectToFieldMapping) attribute).getConverter();
	assertNotNull("converter not assigned", converter);
	assertEquals("Mismatch - converter should have been the EclipseLink JPA wrapper class", ConverterClass.class,
               converter.getClass());
	Field f = ConverterClass.class.getDeclaredField("attributeConverterClassName");
	f.setAccessible(true);
	String attributeConverterClassName = (String) f.get(converter);
	assertNotNull("attributeConverterClassName missing", attributeConverterClassName);
	assertEquals("Converter class incorrect", "org.kuali.rice.krad.data.jpa.converters.BooleanYNConverter",
               attributeConverterClassName);
}
 
Example #5
Source File: EclipseLinkAnnotationMetadataProviderImplTest.java    From rice with Educational Community License v2.0 6 votes vote down vote up
@Test
public void testConvertersEstabished_autoApply() throws Exception {
	ClassDescriptor classDescriptor = jpaMetadataProvider.getClassDescriptor(TestDataObject.class);
	DatabaseMapping attribute = classDescriptor.getMappingForAttributeName("currencyProperty");
	assertEquals("attribute data type mismatch", DirectToFieldMapping.class, attribute.getClass());
	Converter converter = ((org.eclipse.persistence.mappings.DirectToFieldMapping) attribute).getConverter();
	assertNotNull("converter not assigned", converter);
	assertEquals("Mismatch - converter should have been the EclipseLink JPA wrapper class", ConverterClass.class,
               converter.getClass());
	Field f = ConverterClass.class.getDeclaredField("attributeConverterClassName");
	f.setAccessible(true);
	String attributeConverterClassName = (String) f.get(converter);
	assertNotNull("attributeConverterClassName missing", attributeConverterClassName);
	assertEquals("Converter class incorrect", "org.kuali.rice.krad.data.jpa.converters.KualiDecimalConverter",
               attributeConverterClassName);
}
 
Example #6
Source File: EclipseLinkAnnotationMetadataProviderImplTest.java    From rice with Educational Community License v2.0 6 votes vote down vote up
@Test
public void testConvertersEstabished_directAssignment() throws Exception {
	ClassDescriptor classDescriptor = jpaMetadataProvider.getClassDescriptor(TestDataObject.class);
	DatabaseMapping attribute = classDescriptor.getMappingForAttributeName("nonStandardDataType");
	assertEquals("attribute data type mismatch", DirectToFieldMapping.class, attribute.getClass());
	Converter converter = ((org.eclipse.persistence.mappings.DirectToFieldMapping) attribute).getConverter();
	assertNotNull("converter not assigned", converter);
	assertEquals("Mismatch - converter should have been the EclipseLink JPA wrapper class", ConverterClass.class,
               converter.getClass());
	Field f = ConverterClass.class.getDeclaredField("attributeConverterClassName");
	f.setAccessible(true);
	String attributeConverterClassName = (String) f.get(converter);
	assertNotNull("attributeConverterClassName missing", attributeConverterClassName);
	assertEquals("Converter class incorrect", "org.kuali.rice.krad.data.jpa.testbo.NonStandardDataTypeConverter",
               attributeConverterClassName);
}
 
Example #7
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 #8
Source File: EclipseLinkJpaMetadataProviderImpl.java    From rice with Educational Community License v2.0 6 votes vote down vote up
/**
 * Populates the inverse relationship for a given relationship.
 *
 * @param mapping the {@link DatabaseMapping} that defines the relationship.
 * @param relationship the relationship of which to populate the other side.
 */
protected void populateInverseRelationship(DatabaseMapping mapping, MetadataChildBase relationship) {
    DatabaseMapping relationshipPartner = findRelationshipPartner(mapping);
    if (relationshipPartner != null) {
        Class<?> partnerType = relationshipPartner.getDescriptor().getJavaClass();
        DataObjectMetadata partnerMetadata = masterMetadataMap.get(partnerType);
        // if the target metadata is not null, it means that entity has already been processed,
        // so we can go ahead and establish the inverse relationship
        if (partnerMetadata != null) {
            // first check if it's a relationship
            MetadataChildBase relationshipPartnerMetadata =
                    (MetadataChildBase)partnerMetadata.getRelationship(relationshipPartner.getAttributeName());
            if (relationshipPartnerMetadata == null) {
                relationshipPartnerMetadata =
                        (MetadataChildBase)partnerMetadata.getCollection(relationshipPartner.getAttributeName());
            }
            if (relationshipPartnerMetadata != null) {
                relationshipPartnerMetadata.setInverseRelationship(relationship);
                relationship.setInverseRelationship(relationshipPartnerMetadata);
            }

        }
    }
}
 
Example #9
Source File: JPAMDefaultTableGenerator.java    From jeddict with Apache License 2.0 6 votes vote down vote up
private DatabaseMapping getDatabaseMapping(ClassDescriptor descriptor, DatabaseField databaseField) {
    DatabaseMapping databaseMapping = mappings.get(databaseField);
    if (databaseMapping == null) {
        for (DatabaseMapping m : descriptor.getMappings()) {
            for (DatabaseField f : m.getFields()) {
                if (mappings.get(f) == null) {
                    mappings.put(f, m);
                }
                if (databaseField == f) {
                    databaseMapping = m;
                }
            }
        }
    }
    return databaseMapping;
}
 
Example #10
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 #11
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 #12
Source File: FetchTypeMappingProcessor.java    From cuba with Apache License 2.0 6 votes vote down vote up
@Override
public void process(MappingProcessorContext context) {
    DatabaseMapping mapping = context.getMapping();
    String entityClassName = mapping.getDescriptor().getJavaClass().getSimpleName();

    if ((mapping.isOneToOneMapping() || mapping.isOneToManyMapping()
            || mapping.isManyToOneMapping() || mapping.isManyToManyMapping())) {
        if (!mapping.isLazy()) {
            mapping.setIsLazy(true);
            log.warn("EAGER fetch type detected for reference field {} of entity {}; Set to LAZY", mapping.getAttributeName(), entityClassName);
        }
    } else {
        if (mapping.isLazy()) {
            mapping.setIsLazy(false);
            log.warn("LAZY fetch type detected for basic field {} of entity {}; Set to EAGER", mapping.getAttributeName(), entityClassName);
        }
    }
}
 
Example #13
Source File: EmbeddedAttributesMappingProcessor.java    From cuba with Apache License 2.0 6 votes vote down vote up
@Override
public void process(MappingProcessorContext context) {
    DatabaseMapping mapping = context.getMapping();
    if (mapping instanceof AggregateObjectMapping) {
        ClassDescriptor descriptor = mapping.getDescriptor();
        Field referenceField =
                FieldUtils.getFieldsListWithAnnotation(descriptor.getJavaClass(), EmbeddedParameters.class)
                        .stream().filter(f -> f.getName().equals(mapping.getAttributeName())).findFirst().orElse(null);
        if (referenceField != null) {
            EmbeddedParameters embeddedParameters =
                    referenceField.getAnnotation(EmbeddedParameters.class);
            if (!embeddedParameters.nullAllowed())
                ((AggregateObjectMapping) mapping).setIsNullAllowed(false);
        }
    }
}
 
Example #14
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 #15
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 #16
Source File: CamelNamingStrategy.java    From gazpachoquest with GNU General Public License v3.0 5 votes vote down vote up
private void camelCaseToUnderscore(Vector<DatabaseMapping> mappings) {
    for (DatabaseMapping mapping : mappings) {
        DatabaseField field = mapping.getField();
        if (mapping.isDirectToFieldMapping() && !mapping.isPrimaryKeyMapping()) {
            String attributeName = mapping.getAttributeName();
            String underScoredFieldName = camelCaseToUnderscore(attributeName);
            field.setName(underScoredFieldName);
        }
    }
}
 
Example #17
Source File: MapToStringConverter.java    From gazpachoquest with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void initialize(DatabaseMapping mapping, Session session) {
    if (isPostgresProvider(session)) {
        mapping.getField().setSqlType(java.sql.Types.OTHER);
    } else {
        mapping.getField().setSqlType(java.sql.Types.VARCHAR);
    }

}
 
Example #18
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 #19
Source File: StudioEclipseLinkSessionEventListener.java    From cuba with Apache License 2.0 5 votes vote down vote up
@Override
public void preLogin(SessionEvent event) {
    Session session = event.getSession();


    Map<Class, ClassDescriptor> descriptorMap = session.getDescriptors();
    for (Map.Entry<Class, ClassDescriptor> entry : descriptorMap.entrySet()) {
        ClassDescriptor desc = entry.getValue();

        if (SoftDelete.class.isAssignableFrom(desc.getJavaClass())) {
            desc.getQueryManager().setAdditionalCriteria("this.deleteTs is null");
            desc.setDeletePredicate(entity -> entity instanceof SoftDelete &&
                    PersistenceHelper.isLoaded(entity, "deleteTs") &&
                    ((SoftDelete) entity).isDeleted());
        }

        List<DatabaseMapping> mappings = desc.getMappings();
        Class entityClass = entry.getKey();

        for (DatabaseMapping mapping : mappings) {
            if (UUID.class.equals(getFieldType(entityClass, mapping.getAttributeName()))) {
                ((DirectToFieldMapping) mapping).setConverter(UuidConverter.getInstance());
                setDatabaseFieldParameters(session, mapping.getField());
            }
        }
    }
}
 
Example #20
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 #21
Source File: KradEclipseLinkCustomizer.java    From rice with Educational Community License v2.0 5 votes vote down vote up
/**
 * Checks class descriptors for {@link @RemoveMapping} and {@link RemoveMappings} annotations at the class level
 * and removes any specified mappings from the ClassDescriptor.
 *
 * @param session the current session.
 */
protected void handleRemoveMapping(Session session) {
    Map<Class, ClassDescriptor> descriptors = session.getDescriptors();

    if (descriptors == null || descriptors.isEmpty()) {
        return;
    }

    for (ClassDescriptor classDescriptor : descriptors.values()) {
        List<DatabaseMapping> mappingsToRemove = new ArrayList<DatabaseMapping>();
        List<RemoveMapping> removeMappings = scanForRemoveMappings(classDescriptor);

        for (RemoveMapping removeMapping : removeMappings) {
            if (StringUtils.isBlank(removeMapping.name())) {
                throw DescriptorException.attributeNameNotSpecified();
            }

            DatabaseMapping databaseMapping = classDescriptor.getMappingForAttributeName(removeMapping.name());

            if (databaseMapping == null) {
                throw DescriptorException.mappingForAttributeIsMissing(removeMapping.name(), classDescriptor);
            }

            mappingsToRemove.add(databaseMapping);
        }

        for (DatabaseMapping mappingToRemove : mappingsToRemove) {
            classDescriptor.removeMappingForAttributeName(mappingToRemove.getAttributeName());
        }
    }
}
 
Example #22
Source File: UuidConverter.java    From cuba with Apache License 2.0 4 votes vote down vote up
@Override
public void initialize(DatabaseMapping mapping, Session session) {
}
 
Example #23
Source File: MappingProcessorContext.java    From cuba with Apache License 2.0 4 votes vote down vote up
public MappingProcessorContext(DatabaseMapping mapping, Session session) {
    this.mapping = mapping;
    this.session = session;
}
 
Example #24
Source File: MappingProcessorContext.java    From cuba with Apache License 2.0 4 votes vote down vote up
public DatabaseMapping getMapping() {
    return mapping;
}
 
Example #25
Source File: EclipseLinkJpaMetadataProviderImpl.java    From rice with Educational Community License v2.0 4 votes vote down vote up
/**
    * {@inheritDoc}
    */
@Override
protected void populateImplementationSpecificAttributeLevelMetadata(DataObjectAttributeImpl attribute,
		SingularAttribute<?, ?> attr) {

	if (attr instanceof SingularAttributeImpl) {
		DatabaseMapping mapping = ((SingularAttributeImpl<?, ?>) attr).getMapping();
		if (mapping != null && mapping.getField() != null) {
               attribute.setReadOnly(mapping.isReadOnly());
			attribute.setBackingObjectName(mapping.getField().getName());
			if (mapping.getField().getLength() != 0) {
				attribute.setMaxLength((long) mapping.getField().getLength());
			}

			// Special check on the converters to attempt to default secure attributes from being shown on the UI
			// We check for a converter which has "encrypt" in its name and auto-set the attribute security
			// to mask the attribute.
			if (mapping instanceof DirectToFieldMapping) {
				Converter converter = ((DirectToFieldMapping) mapping).getConverter();
				// ConverterClass is the internal wrapper EclipseLink uses to wrap the JPA AttributeConverter
				// classes
				// and make them conform to the EclipseLink internal API
				if (converter != null && converter instanceof ConverterClass) {
					// Unfortunately, there is no access to the actual converter class, so we have to hack it
					try {
						Field f = ConverterClass.class.getDeclaredField("attributeConverterClassName");
						f.setAccessible(true);
						String attributeConverterClassName = (String) f.get(converter);
						if (StringUtils.containsIgnoreCase(attributeConverterClassName, "encrypt")) {
							attribute.setSensitive(true);
						}
					} catch (Exception e) {
						LOG.warn("Unable to access the converter name for attribute: "
								+ attribute.getOwningType().getName() + "." + attribute.getName()
								+ "  Skipping attempt to detect converter.");
					}
				}
			}

		}
	}
}
 
Example #26
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 #27
Source File: DefaultEmbeddedAttributeSpecAccessor.java    From jeddict with Apache License 2.0 4 votes vote down vote up
@Override
protected void setMapping(DatabaseMapping mapping) {
    super.setMapping(mapping);
}
 
Example #28
Source File: DBMetadataDescriptor.java    From jeddict with Apache License 2.0 4 votes vote down vote up
/**
 * @param parentClassMapping the parentClassMapping to set
 */
public void setParentClassMapping(List<DatabaseMapping> parentClassMapping) {
    ((DBRelationalDescriptor) getClassDescriptor()).setParentClassMapping(parentClassMapping);
}
 
Example #29
Source File: DBRelationalDescriptor.java    From jeddict with Apache License 2.0 4 votes vote down vote up
/**
 * @param parentClassMapping the parentClassMapping to set
 */
public void setParentClassMapping(List<DatabaseMapping> parentClassMapping) {
    this.parentClassMapping = parentClassMapping;
}
 
Example #30
Source File: DBRelationalDescriptor.java    From jeddict with Apache License 2.0 4 votes vote down vote up
/**
 * @return the parentClassMapping
 */
public List<DatabaseMapping> getParentClassMapping() {
    return parentClassMapping;
}