Search in sources :

Example 1 with Session

use of org.eclipse.persistence.sessions.Session in project cuba by cuba-platform.

the class StudioEclipseLinkSessionEventListener method preLogin.

@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());
            }
        }
    }
}
Also used : DirectToFieldMapping(org.eclipse.persistence.mappings.DirectToFieldMapping) ClassDescriptor(org.eclipse.persistence.descriptors.ClassDescriptor) SoftDelete(com.haulmont.cuba.core.entity.SoftDelete) DatabaseMapping(org.eclipse.persistence.mappings.DatabaseMapping) Map(java.util.Map) Session(org.eclipse.persistence.sessions.Session)

Example 2 with Session

use of org.eclipse.persistence.sessions.Session in project cuba by cuba-platform.

the class PersistenceTools method getReferenceId.

/**
 * 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);
    }
}
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 3 with Session

use of org.eclipse.persistence.sessions.Session in project cuba by cuba-platform.

the class UuidMappingProcessor method process.

@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);
            }
        }
    }
}
Also used : DirectToFieldMapping(org.eclipse.persistence.mappings.DirectToFieldMapping) MetaClass(com.haulmont.chile.core.model.MetaClass) DatabaseField(org.eclipse.persistence.internal.helper.DatabaseField) DatabaseMapping(org.eclipse.persistence.mappings.DatabaseMapping) MetaProperty(com.haulmont.chile.core.model.MetaProperty) Session(org.eclipse.persistence.sessions.Session)

Example 4 with Session

use of org.eclipse.persistence.sessions.Session in project cuba by cuba-platform.

the class EclipseLinkSessionEventListener method preLogin.

@Override
public void preLogin(SessionEvent event) {
    Session session = event.getSession();
    boolean useJoinSubclasses = useJoinSubclasses();
    boolean hasMultipleTableConstraintDependency = hasMultipleTableConstraintDependency();
    setPrintInnerJoinOnClause(session);
    if (useJoinSubclasses) {
        setJoinSubclasses(session);
    }
    List<Pair<Class, String>> missingEnhancements = new ArrayList<>();
    Map<String, ClassDescriptor> mappedSuperclassDescriptorMap = session.getProject().getMappedSuperclassDescriptors();
    for (Map.Entry<String, ClassDescriptor> entry : mappedSuperclassDescriptorMap.entrySet()) {
        try {
            Class javaClass = getClass().getClassLoader().loadClass(entry.getKey());
            enhancementCheck(javaClass, missingEnhancements);
        } catch (ClassNotFoundException e) {
            log.warn("MappedSuperclass {} was not found by ClassLoader", entry.getKey());
        }
    }
    Map<Class, ClassDescriptor> descriptorMap = session.getDescriptors();
    for (Map.Entry<Class, ClassDescriptor> entry : descriptorMap.entrySet()) {
        MetaClass metaClass = metadata.getSession().getClassNN(entry.getKey());
        ClassDescriptor desc = entry.getValue();
        enhancementCheck(entry.getKey(), missingEnhancements);
        setCacheable(metaClass, desc, session);
        if (hasMultipleTableConstraintDependency) {
            setMultipleTableConstraintDependency(metaClass, desc);
        }
        if (useJoinSubclasses) {
            setJoinSubclasses(metaClass, desc);
        }
        if (Entity.class.isAssignableFrom(desc.getJavaClass())) {
            // set DescriptorEventManager that doesn't invoke listeners for base classes
            desc.setEventManager(new DescriptorEventManagerWrapper(desc.getDescriptorEventManager()));
            desc.getEventManager().addListener(descriptorEventListener);
        }
        setAdditionalCriteria(desc);
        if (SoftDelete.class.isAssignableFrom(desc.getJavaClass())) {
            desc.setDeletePredicate(entity -> entity instanceof SoftDelete && PersistenceHelper.isLoaded(entity, "deleteTs") && ((SoftDelete) entity).isDeleted());
        }
        Map<String, MappingProcessor> mappingProcessors = AppBeans.getAll(MappingProcessor.class);
        for (DatabaseMapping mapping : desc.getMappings()) {
            MappingProcessorContext mappingProcessorCtx = new MappingProcessorContext(mapping, session);
            for (MappingProcessor mp : mappingProcessors.values()) {
                log.debug("{} mapping processor is started", mp.getClass());
                mp.process(mappingProcessorCtx);
                log.debug("{} mapping processor is finished", mp.getClass());
            }
        }
    }
    logCheckResult(missingEnhancements);
}
Also used : ClassDescriptor(org.eclipse.persistence.descriptors.ClassDescriptor) SoftDelete(com.haulmont.cuba.core.entity.SoftDelete) MappingProcessorContext(com.haulmont.cuba.core.sys.persistence.mapping.MappingProcessorContext) ArrayList(java.util.ArrayList) DatabaseMapping(org.eclipse.persistence.mappings.DatabaseMapping) MetaClass(com.haulmont.chile.core.model.MetaClass) MappingProcessor(com.haulmont.cuba.core.sys.persistence.mapping.MappingProcessor) MetaClass(com.haulmont.chile.core.model.MetaClass) Map(java.util.Map) Session(org.eclipse.persistence.sessions.Session) Pair(com.haulmont.bali.datastruct.Pair)

Aggregations

DatabaseMapping (org.eclipse.persistence.mappings.DatabaseMapping)4 Session (org.eclipse.persistence.sessions.Session)4 MetaClass (com.haulmont.chile.core.model.MetaClass)3 ClassDescriptor (org.eclipse.persistence.descriptors.ClassDescriptor)3 MetaProperty (com.haulmont.chile.core.model.MetaProperty)2 SoftDelete (com.haulmont.cuba.core.entity.SoftDelete)2 Map (java.util.Map)2 DatabaseField (org.eclipse.persistence.internal.helper.DatabaseField)2 DirectToFieldMapping (org.eclipse.persistence.mappings.DirectToFieldMapping)2 Pair (com.haulmont.bali.datastruct.Pair)1 BaseGenericIdEntity (com.haulmont.cuba.core.entity.BaseGenericIdEntity)1 Entity (com.haulmont.cuba.core.entity.Entity)1 MappingProcessor (com.haulmont.cuba.core.sys.persistence.mapping.MappingProcessor)1 MappingProcessorContext (com.haulmont.cuba.core.sys.persistence.mapping.MappingProcessorContext)1 Method (java.lang.reflect.Method)1 ArrayList (java.util.ArrayList)1 ValueHolderInterface (org.eclipse.persistence.indirection.ValueHolderInterface)1 DatabaseValueHolder (org.eclipse.persistence.internal.indirection.DatabaseValueHolder)1 AbstractRecord (org.eclipse.persistence.internal.sessions.AbstractRecord)1 Converter (org.eclipse.persistence.mappings.converters.Converter)1