Search in sources :

Example 1 with DatabaseMapping

use of org.eclipse.persistence.mappings.DatabaseMapping in project cuba by cuba-platform.

the class PersistenceTools method getReferenceId.

/**
 * Returns an ID of directly referenced entity without loading it from DB.
 *
 * 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 (!PersistenceHelper.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.getAttributeNames().contains(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);
    }
}
Also used : BaseGenericIdEntity(com.haulmont.cuba.core.entity.BaseGenericIdEntity) Entity(com.haulmont.cuba.core.entity.Entity) ClassDescriptor(org.eclipse.persistence.descriptors.ClassDescriptor) AbstractRecord(org.eclipse.persistence.internal.sessions.AbstractRecord) DatabaseMapping(org.eclipse.persistence.mappings.DatabaseMapping) Method(java.lang.reflect.Method) AbstractColumnMapping(org.eclipse.persistence.mappings.foundation.AbstractColumnMapping) FetchGroupTracker(org.eclipse.persistence.queries.FetchGroupTracker) DatabaseValueHolder(org.eclipse.persistence.internal.indirection.DatabaseValueHolder) MetaClass(com.haulmont.chile.core.model.MetaClass) ValueHolderInterface(org.eclipse.persistence.indirection.ValueHolderInterface) DatabaseField(org.eclipse.persistence.internal.helper.DatabaseField) FetchGroup(org.eclipse.persistence.queries.FetchGroup) Converter(org.eclipse.persistence.mappings.converters.Converter) MetaProperty(com.haulmont.chile.core.model.MetaProperty) Session(org.eclipse.persistence.sessions.Session)

Example 2 with DatabaseMapping

use of org.eclipse.persistence.mappings.DatabaseMapping in project tomee by apache.

the class PrefixSessionCustomizer method customize.

@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());
        }
    }
}
Also used : ManyToManyMapping(org.eclipse.persistence.mappings.ManyToManyMapping) ClassDescriptor(org.eclipse.persistence.descriptors.ClassDescriptor) ArrayList(java.util.ArrayList) DatabaseTable(org.eclipse.persistence.internal.helper.DatabaseTable) DatabaseMapping(org.eclipse.persistence.mappings.DatabaseMapping) TableSequence(org.eclipse.persistence.sequencing.TableSequence) Sequence(org.eclipse.persistence.sequencing.Sequence) Properties(java.util.Properties) DirectCollectionMapping(org.eclipse.persistence.mappings.DirectCollectionMapping) TableSequence(org.eclipse.persistence.sequencing.TableSequence)

Aggregations

ClassDescriptor (org.eclipse.persistence.descriptors.ClassDescriptor)2 DatabaseMapping (org.eclipse.persistence.mappings.DatabaseMapping)2 MetaClass (com.haulmont.chile.core.model.MetaClass)1 MetaProperty (com.haulmont.chile.core.model.MetaProperty)1 BaseGenericIdEntity (com.haulmont.cuba.core.entity.BaseGenericIdEntity)1 Entity (com.haulmont.cuba.core.entity.Entity)1 Method (java.lang.reflect.Method)1 ArrayList (java.util.ArrayList)1 Properties (java.util.Properties)1 ValueHolderInterface (org.eclipse.persistence.indirection.ValueHolderInterface)1 DatabaseField (org.eclipse.persistence.internal.helper.DatabaseField)1 DatabaseTable (org.eclipse.persistence.internal.helper.DatabaseTable)1 DatabaseValueHolder (org.eclipse.persistence.internal.indirection.DatabaseValueHolder)1 AbstractRecord (org.eclipse.persistence.internal.sessions.AbstractRecord)1 DirectCollectionMapping (org.eclipse.persistence.mappings.DirectCollectionMapping)1 ManyToManyMapping (org.eclipse.persistence.mappings.ManyToManyMapping)1 Converter (org.eclipse.persistence.mappings.converters.Converter)1 AbstractColumnMapping (org.eclipse.persistence.mappings.foundation.AbstractColumnMapping)1 FetchGroup (org.eclipse.persistence.queries.FetchGroup)1 FetchGroupTracker (org.eclipse.persistence.queries.FetchGroupTracker)1