org.eclipse.persistence.descriptors.ClassDescriptor Java Examples

The following examples show how to use org.eclipse.persistence.descriptors.ClassDescriptor. 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: 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 #2
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 #3
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 #4
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 #5
Source File: KradEclipseLinkCustomizer.java    From rice with Educational Community License v2.0 6 votes vote down vote up
/**
 * Load Query Customizer based on annotations on fields and call customizer to modify descriptor.
 *
 * @param session the EclipseLink session.
 */
protected void loadQueryCustomizers(Session session) {
    Map<Class, ClassDescriptor> descriptors = session.getDescriptors();
    for (Class<?> entityClass : descriptors.keySet()) {
        for (Field field : entityClass.getDeclaredFields()) {
            String queryCustEntry = entityClass.getName() + "_" + field.getName();
            buildQueryCustomizers(entityClass,field,queryCustEntry);

            List<FilterGenerator> queryCustomizers = queryCustomizerMap.get(queryCustEntry);
            if (queryCustomizers != null && !queryCustomizers.isEmpty()) {
                Filter.customizeField(queryCustomizers, descriptors.get(entityClass), field.getName());
            }
        }
    }

}
 
Example #6
Source File: KradEclipseLinkCustomizer.java    From rice with Educational Community License v2.0 6 votes vote down vote up
/**
 * Checks class descriptors for {@link @DisableVersioning} annotations at the class level and removes the version
 * database mapping for optimistic locking.
 *
 * @param session the current session.
 */
protected void handleDisableVersioning(Session session) {
    Map<Class, ClassDescriptor> descriptors = session.getDescriptors();

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

    for (ClassDescriptor classDescriptor : descriptors.values()) {
        if (classDescriptor != null && AnnotationUtils.findAnnotation(classDescriptor.getJavaClass(),
                DisableVersioning.class) != null) {
            OptimisticLockingPolicy olPolicy = classDescriptor.getOptimisticLockingPolicy();
            if (olPolicy != null) {
                classDescriptor.setOptimisticLockingPolicy(null);
            }
        }
    }
}
 
Example #7
Source File: KradEclipseLinkCustomizer.java    From rice with Educational Community License v2.0 6 votes vote down vote up
/**
 * Gets any {@link RemoveMapping}s out of the given {@link ClassDescriptor}.
 *
 * @param classDescriptor the {@link ClassDescriptor} to scan.
 * @return a list of {@link RemoveMapping}s from the given {@link ClassDescriptor}.
 */
protected List<RemoveMapping> scanForRemoveMappings(ClassDescriptor classDescriptor) {
    List<RemoveMapping> removeMappings = new ArrayList<RemoveMapping>();
    RemoveMappings removeMappingsAnnotation = AnnotationUtils.findAnnotation(classDescriptor.getJavaClass(),
            RemoveMappings.class);
    if (removeMappingsAnnotation == null) {
        RemoveMapping removeMappingAnnotation = AnnotationUtils.findAnnotation(classDescriptor.getJavaClass(),
                RemoveMapping.class);
        if (removeMappingAnnotation != null) {
            removeMappings.add(removeMappingAnnotation);
        }
    } else {
        for (RemoveMapping removeMapping : removeMappingsAnnotation.value()) {
            removeMappings.add(removeMapping);
        }
    }
    return removeMappings;
}
 
Example #8
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 #9
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 #10
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 #11
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 #12
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 #13
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 #14
Source File: JPAMSchemaManager.java    From jeddict with Apache License 2.0 5 votes vote down vote up
/**
 * INTERNAL: Build the sequence definitions.
 */
protected HashSet<SequenceDefinition> buildSequenceDefinitions() {
    // Remember the processed - to handle each sequence just once.
    HashSet processedSequenceNames = new HashSet();
    HashSet<SequenceDefinition> sequenceDefinitions = new HashSet<>();

    for (ClassDescriptor descriptor : getSession().getDescriptors().values()) {
        if (descriptor.usesSequenceNumbers()) {
            String seqName = descriptor.getSequenceNumberName();

            if (seqName == null) {
                seqName = getSession().getDatasourcePlatform().getDefaultSequence().getName();
            }

            if (!processedSequenceNames.contains(seqName)) {
                processedSequenceNames.add(seqName);

                Sequence sequence = getSession().getDatasourcePlatform().getSequence(seqName);
                SequenceDefinition sequenceDefinition = buildSequenceDefinition(sequence);

                if (sequenceDefinition != null) {
                    sequenceDefinitions.add(sequenceDefinition);
                }
            }
        }
    }

    return sequenceDefinitions;
}
 
Example #15
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 #16
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 #17
Source File: JPAMDynamicTypeBuilder.java    From jeddict with Apache License 2.0 5 votes vote down vote up
@Override
protected void configure(ClassDescriptor descriptor, String... tableNames) {
    DBRelationalDescriptor relationDescriptor = (DBRelationalDescriptor) descriptor;
    // Configure Table names if provided
    if (tableNames != null) {
        if (tableNames.length == 0) {
            //Fix for : https://github.com/jeddict/jeddict/issues/1
            // If ClassDescriptor is entity then don't make it Aggregate
            if (descriptor.getTables().size() == 0 && !(relationDescriptor.getAccessor() instanceof EntitySpecAccessor)) {
                descriptor.descriptorIsAggregate();
            }
        } else {
            for (int index = 0; index < tableNames.length; index++) {
                descriptor.addTableName(tableNames[index]);
            }
        }

    }

    for (int index = 0; index < descriptor.getMappings().size(); index++) {
        addMapping(descriptor.getMappings().get(index));
    }

    descriptor.setProperty(DynamicType.DESCRIPTOR_PROPERTY, entityType);


    if (descriptor.getCMPPolicy() == null) {
        descriptor.setCMPPolicy(new DynamicIdentityPolicy());
    }
}
 
Example #18
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 #19
Source File: EclipseLinkSessionEventListener.java    From cuba with Apache License 2.0 5 votes vote down vote up
private void setAdditionalCriteria(ClassDescriptor desc) {
    Map<String, AdditionalCriteriaProvider> additionalCriteriaProviderMap = AppBeans.getAll(AdditionalCriteriaProvider.class);

    StringBuilder criteriaBuilder = new StringBuilder();
    additionalCriteriaProviderMap.values().stream()
            .filter(item -> item.requiresAdditionalCriteria(desc.getJavaClass()))
            .forEach(additionalCriteriaProvider ->
                    criteriaBuilder.append(additionalCriteriaProvider.getAdditionalCriteria(desc.getJavaClass())).append(" AND")
            );

    if (criteriaBuilder.length() != 0) {
        String additionalCriteriaResult = criteriaBuilder.substring(0, criteriaBuilder.length() - 4);
        desc.getQueryManager().setAdditionalCriteria(additionalCriteriaResult);
    }
}
 
Example #20
Source File: EclipseLinkSessionEventListener.java    From cuba with Apache License 2.0 5 votes vote down vote up
private void setCacheable(MetaClass metaClass, ClassDescriptor desc, Session session) {
    String property = (String) session.getProperty("eclipselink.cache.shared.default");
    boolean defaultCache = property == null || Boolean.valueOf(property);

    if ((defaultCache && !desc.isIsolated())
            || desc.getCacheIsolation() == CacheIsolationType.SHARED
            || desc.getCacheIsolation() == CacheIsolationType.PROTECTED) {
        metaClass.getAnnotations().put("cacheable", true);
        desc.getCachePolicy().setCacheCoordinationType(CacheCoordinationType.INVALIDATE_CHANGED_OBJECTS);
    }
}
 
Example #21
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 #22
Source File: PersistenceTools.java    From cuba with Apache License 2.0 4 votes vote down vote up
/**
 * Returns an ID of directly referenced entity without loading it from DB.
 * <p>
 * If the view does not contain the reference and {@link View#loadPartialEntities()} is true,
 * the returned {@link RefId} will have {@link RefId#isLoaded()} = false.
 *
 * <p>Usage example:
 * <pre>
 *   PersistenceTools.RefId refId = persistenceTools.getReferenceId(doc, "currency");
 *   if (refId.isLoaded()) {
 *       String currencyCode = (String) refId.getValue();
 *   }
 * </pre>
 *
 * @param entity   entity instance in managed state
 * @param property name of reference property
 * @return {@link RefId} instance which contains the referenced entity ID
 * @throws IllegalArgumentException if the specified property is not a reference
 * @throws IllegalStateException    if the entity is not in Managed state
 * @throws RuntimeException         if anything goes wrong when retrieving the ID
 */
public RefId getReferenceId(BaseGenericIdEntity entity, String property) {
    MetaClass metaClass = metadata.getClassNN(entity.getClass());
    MetaProperty metaProperty = metaClass.getPropertyNN(property);

    if (!metaProperty.getRange().isClass() || metaProperty.getRange().getCardinality().isMany())
        throw new IllegalArgumentException("Property is not a reference");

    if (!entityStates.isManaged(entity))
        throw new IllegalStateException("Entity must be in managed state");

    String[] inaccessibleAttributes = BaseEntityInternalAccess.getInaccessibleAttributes(entity);
    if (inaccessibleAttributes != null) {
        for (String inaccessibleAttr : inaccessibleAttributes) {
            if (inaccessibleAttr.equals(property))
                return RefId.createNotLoaded(property);
        }
    }

    if (entity instanceof FetchGroupTracker) {
        FetchGroup fetchGroup = ((FetchGroupTracker) entity)._persistence_getFetchGroup();
        if (fetchGroup != null) {
            if (!fetchGroup.containsAttributeInternal(property))
                return RefId.createNotLoaded(property);
            else {
                Entity refEntity = (Entity) entity.getValue(property);
                return RefId.create(property, refEntity == null ? null : refEntity.getId());
            }
        }
    }

    try {
        Class<?> declaringClass = metaProperty.getDeclaringClass();
        if (declaringClass == null) {
            throw new RuntimeException("Property does not belong to persistent class");
        }

        Method vhMethod = declaringClass.getDeclaredMethod(String.format("_persistence_get_%s_vh", property));
        vhMethod.setAccessible(true);

        ValueHolderInterface vh = (ValueHolderInterface) vhMethod.invoke(entity);
        if (vh instanceof DatabaseValueHolder) {
            AbstractRecord row = ((DatabaseValueHolder) vh).getRow();
            if (row != null) {
                Session session = persistence.getEntityManager().getDelegate().unwrap(Session.class);
                ClassDescriptor descriptor = session.getDescriptor(entity);
                DatabaseMapping mapping = descriptor.getMappingForAttributeName(property);
                Vector<DatabaseField> fields = mapping.getFields();
                if (fields.size() != 1) {
                    throw new IllegalStateException("Invalid number of columns in mapping: " + fields);
                }
                Object value = row.get(fields.get(0));
                if (value != null) {
                    ClassDescriptor refDescriptor = mapping.getReferenceDescriptor();
                    DatabaseMapping refMapping = refDescriptor.getMappingForAttributeName(metadata.getTools().getPrimaryKeyName(metaClass));
                    if (refMapping instanceof AbstractColumnMapping) {
                        Converter converter = ((AbstractColumnMapping) refMapping).getConverter();
                        if (converter != null) {
                            return RefId.create(property, converter.convertDataValueToObjectValue(value, session));
                        }
                    }
                }
                return RefId.create(property, value);
            } else {
                return RefId.create(property, null);
            }
        }
        return RefId.createNotLoaded(property);
    } catch (Exception e) {
        throw new RuntimeException(
                String.format("Error retrieving reference ID from %s.%s", entity.getClass().getSimpleName(), property),
                e);
    }
}
 
Example #23
Source File: CubaEntityFetchGroup.java    From cuba with Apache License 2.0 4 votes vote down vote up
@Override
public CoreAttributeGroup cloneWithSameAttributes(Map<CoreAttributeGroup<AttributeItem, ClassDescriptor>, CoreAttributeGroup<AttributeItem, ClassDescriptor>> cloneMap) {
    return new CubaEntityFetchGroup(wrappedFetchGroup.cloneWithSameAttributes());
}
 
Example #24
Source File: QuestionnaireAnswersRepositoryImpl.java    From gazpachoquest with GNU General Public License v3.0 4 votes vote down vote up
private DynamicEntity newInstance(final String entityAlias) {
    final JPADynamicHelper helper = new JPADynamicHelper(entityManager);
    final ClassDescriptor descriptor = helper.getSession().getDescriptorForAlias(entityAlias);
    Assert.notNull(descriptor, " Not found dynamic class descriptor for entity: " + entityAlias);
    return (DynamicEntity) descriptor.getInstantiationPolicy().buildNewInstance();
}
 
Example #25
Source File: CubaEntityFetchGroup.java    From cuba with Apache License 2.0 4 votes vote down vote up
@Override
public AttributeGroup findGroup(ClassDescriptor type) {
    return wrappedFetchGroup.findGroup(type);
}
 
Example #26
Source File: CubaEntityFetchGroup.java    From cuba with Apache License 2.0 4 votes vote down vote up
@Override
public CoreAttributeGroup clone(Map<CoreAttributeGroup<AttributeItem, ClassDescriptor>, CoreAttributeGroup<AttributeItem, ClassDescriptor>> cloneMap) {
    return wrappedFetchGroup.clone(cloneMap);
}
 
Example #27
Source File: EclipseLinkSessionEventListener.java    From cuba with Apache License 2.0 4 votes vote down vote up
private void setMultipleTableConstraintDependency(MetaClass metaClass, ClassDescriptor desc) {
    InheritancePolicy policy = desc.getInheritancePolicyOrNull();
    if (policy != null && policy.isJoinedStrategy() && policy.getParentClass() != null) {
        desc.setHasMultipleTableConstraintDependecy(true);
    }
}
 
Example #28
Source File: EntityCacheTestClass.java    From cuba with Apache License 2.0 4 votes vote down vote up
@BeforeEach
    public void setUp() throws Exception {
        assertTrue(cont.getSpringAppContext() == AppContext.getApplicationContext());

        try (Transaction tx = cont.persistence().createTransaction()) {
            EntityManagerFactory emf = cont.entityManager().getDelegate().getEntityManagerFactory();

            assertTrue(cont.metadata().getTools().isCacheable(cont.metadata().getClassNN(User.class)));
            assertFalse(cont.metadata().getTools().isCacheable(cont.metadata().getClassNN(UserSubstitution.class)));

            ServerSession serverSession = ((EntityManagerFactoryDelegate) emf).getServerSession();
            ClassDescriptor descriptor = serverSession.getDescriptor(User.class);
            assertEquals(500, descriptor.getCachePolicy().getIdentityMapSize());

//            assertTrue(Boolean.valueOf((String) emf.getProperties().get("eclipselink.cache.shared.default")));
//            assertTrue(Boolean.valueOf((String) emf.getProperties().get("eclipselink.cache.shared.sec$User")));


            this.cache = (JpaCache) emf.getCache();

            group = cont.metadata().create(Group.class);
            group.setName("group-" + group.getId());
            cont.entityManager().persist(group);

            user = cont.metadata().create(User.class);
            user.setLogin("ECTest-" + user.getId());
            user.setPassword("111");
            user.setGroup(group);
            cont.entityManager().persist(user);

            user2 = cont.metadata().create(User.class);
            user2.setLogin("ECTest-" + user2.getId());
            user2.setPassword("111");
            user2.setGroup(group);
            cont.entityManager().persist(user2);

            role = cont.metadata().create(Role.class);
            role.setName("Test role");
            role.setDescription("Test role descr");
            cont.entityManager().persist(role);

            userRole = cont.metadata().create(UserRole.class);
            userRole.setRole(role);
            userRole.setUser(user);
            cont.entityManager().persist(userRole);

            userSetting = cont.metadata().create(UserSetting.class);
            userSetting.setUser(user);
            cont.entityManager().persist(userSetting);

            userSubstitution = cont.metadata().create(UserSubstitution.class);
            userSubstitution.setUser(user);
            userSubstitution.setSubstitutedUser(user2);
            cont.entityManager().persist(userSubstitution);

            compositeOne = cont.metadata().create(CompositeOne.class);
            compositeOne.setName("compositeOne");
            cont.entityManager().persist(compositeOne);

            compositeTwo = cont.metadata().create(CompositeTwo.class);
            compositeTwo.setName("compositeTwo");
            cont.entityManager().persist(compositeTwo);

            compositePropertyOne = cont.metadata().create(CompositePropertyOne.class);
            compositePropertyOne.setName("compositePropertyOne");
            compositePropertyOne.setCompositeOne(compositeOne);
            compositePropertyOne.setCompositeTwo(compositeTwo);
            cont.entityManager().persist(compositePropertyOne);

            compositePropertyTwo = cont.metadata().create(CompositePropertyTwo.class);
            compositePropertyTwo.setName("compositePropertyTwo");
            compositePropertyTwo.setCompositeTwo(compositeTwo);
            cont.entityManager().persist(compositePropertyTwo);

            tx.commit();
        }
        cache.clear();
    }
 
Example #29
Source File: QueryCacheTestClass.java    From cuba with Apache License 2.0 4 votes vote down vote up
@BeforeEach
public void setUp() throws Exception {
    assertTrue(cont.getSpringAppContext() == AppContext.getApplicationContext());
    queryCache = AppBeans.get(QueryCache.NAME);
    try (Transaction tx = cont.persistence().createTransaction()) {
        EntityManagerFactory emf = cont.entityManager().getDelegate().getEntityManagerFactory();

        assertTrue(cont.metadata().getTools().isCacheable(cont.metadata().getClassNN(User.class)));
        assertFalse(cont.metadata().getTools().isCacheable(cont.metadata().getClassNN(UserSubstitution.class)));

        ServerSession serverSession = ((EntityManagerFactoryDelegate) emf).getServerSession();
        ClassDescriptor descriptor = serverSession.getDescriptor(User.class);
        assertEquals(500, descriptor.getCachePolicy().getIdentityMapSize());

        this.cache = (JpaCache) emf.getCache();

        group = cont.metadata().create(Group.class);
        group.setName("group-" + group.getId());
        cont.entityManager().persist(group);

        user = cont.metadata().create(User.class);
        user.setLogin("ECTest-" + user.getId());
        user.setPassword("111");
        user.setName("1");
        user.setGroup(group);
        cont.entityManager().persist(user);

        user2 = cont.metadata().create(User.class);
        user2.setLogin("ECTest-" + user2.getId());
        user2.setPassword("111");
        user2.setName("2");
        user2.setGroup(group);
        cont.entityManager().persist(user2);

        user3 = cont.metadata().create(User.class);
        user3.setLogin("ECTest-" + user3.getId());
        user3.setPassword("111");
        user3.setGroup(group);
        cont.entityManager().persist(user3);

        role = cont.metadata().create(Role.class);
        role.setName("TestRole");
        role.setDescription("Test role descr");
        cont.entityManager().persist(role);

        userRole = cont.metadata().create(UserRole.class);
        userRole.setRole(role);
        userRole.setUser(user);
        cont.entityManager().persist(userRole);

        userSetting = cont.metadata().create(UserSetting.class);
        userSetting.setUser(user);
        cont.entityManager().persist(userSetting);

        tx.commit();
    }

    try (Transaction tx = cont.persistence().createTransaction()) {
        cont.entityManager().remove(user3);
        tx.commit();
    }
    cache.clear();
    queryCache.invalidateAll();
}
 
Example #30
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);
}