org.eclipse.persistence.mappings.DirectToFieldMapping Java Examples

The following examples show how to use org.eclipse.persistence.mappings.DirectToFieldMapping. 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: 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 #2
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 #3
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 #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: 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 #6
Source File: JPAMDefaultTableGenerator.java    From jeddict with Apache License 2.0 5 votes vote down vote up
/**
 * Reset field type to use BLOB/CLOB with type conversion mapping fix for 4k
 * oracle thin driver bug.
 */
protected void resetFieldTypeForLOB(DirectToFieldMapping mapping) {
    if (mapping.getFieldClassification().getName().equals("java.sql.Blob")) {
        //allow the platform to figure out what database field type gonna be used.
        //For example, Oracle9 will generate BLOB type, SQL Server generats IMAGE.
        getFieldDefFromDBField(mapping.getField()).setType(Byte[].class);
    } else if (mapping.getFieldClassification().getName().equals("java.sql.Clob")) {
        //allow the platform to figure out what database field type gonna be used.
        //For example, Oracle9 will generate CLOB type. SQL Server generats TEXT.
        getFieldDefFromDBField(mapping.getField()).setType(Character[].class);
    }
}
 
Example #7
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 #8
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.");
					}
				}
			}

		}
	}
}