Search in sources :

Example 26 with MetaProperty

use of com.haulmont.chile.core.model.MetaProperty in project cuba by cuba-platform.

the class CrossDataStoreReferenceLoader method loadBatch.

private void loadBatch(CrossDataStoreProperty crossDataStoreProperty, List<Entity> entities) {
    List<Object> idList = entities.stream().map(e -> e.getValue(crossDataStoreProperty.relatedPropertyName)).filter(Objects::nonNull).distinct().collect(Collectors.toList());
    if (idList.isEmpty())
        return;
    MetaClass cdsrMetaClass = crossDataStoreProperty.property.getRange().asClass();
    LoadContext<Entity> loadContext = new LoadContext<>(cdsrMetaClass);
    MetaProperty primaryKeyProperty = metadataTools.getPrimaryKeyProperty(cdsrMetaClass);
    if (primaryKeyProperty == null || !primaryKeyProperty.getRange().isClass()) {
        String queryString = String.format("select e from %s e where e.%s in :idList", cdsrMetaClass, crossDataStoreProperty.primaryKeyName);
        loadContext.setQuery(LoadContext.createQuery(queryString).setParameter("idList", idList));
    } else {
        // composite key entity
        StringBuilder sb = new StringBuilder("select e from ");
        sb.append(cdsrMetaClass).append(" e where ");
        MetaClass idMetaClass = primaryKeyProperty.getRange().asClass();
        for (Iterator<MetaProperty> it = idMetaClass.getProperties().iterator(); it.hasNext(); ) {
            MetaProperty property = it.next();
            sb.append("e.").append(crossDataStoreProperty.primaryKeyName).append(".").append(property.getName());
            sb.append(" in :list_").append(property.getName());
            if (it.hasNext())
                sb.append(" and ");
        }
        LoadContext.Query query = LoadContext.createQuery(sb.toString());
        for (MetaProperty property : idMetaClass.getProperties()) {
            List<Object> propList = idList.stream().map(o -> ((Entity) o).getValue(property.getName())).collect(Collectors.toList());
            query.setParameter("list_" + property.getName(), propList);
        }
        loadContext.setQuery(query);
    }
    loadContext.setView(crossDataStoreProperty.viewProperty.getView());
    List<Entity> loadedEntities = dataManager.loadList(loadContext);
    for (Entity entity : entities) {
        Object relatedPropertyValue = entity.getValue(crossDataStoreProperty.relatedPropertyName);
        loadedEntities.stream().filter(e -> {
            Object id = e.getId() instanceof IdProxy ? ((IdProxy) e.getId()).getNN() : e.getId();
            return id.equals(relatedPropertyValue);
        }).findAny().ifPresent(e -> entity.setValue(crossDataStoreProperty.property.getName(), e));
    }
}
Also used : java.util(java.util) Logger(org.slf4j.Logger) MetaProperty(com.haulmont.chile.core.model.MetaProperty) LoggerFactory(org.slf4j.LoggerFactory) Collectors(java.util.stream.Collectors) Sets(com.google.common.collect.Sets) Preconditions(com.haulmont.bali.util.Preconditions) MetaClass(com.haulmont.chile.core.model.MetaClass) Scope(org.springframework.context.annotation.Scope) com.haulmont.cuba.core.global(com.haulmont.cuba.core.global) Inject(javax.inject.Inject) Component(org.springframework.stereotype.Component) IdProxy(com.haulmont.cuba.core.entity.IdProxy) Entity(com.haulmont.cuba.core.entity.Entity) Entity(com.haulmont.cuba.core.entity.Entity) MetaClass(com.haulmont.chile.core.model.MetaClass) IdProxy(com.haulmont.cuba.core.entity.IdProxy) MetaProperty(com.haulmont.chile.core.model.MetaProperty)

Example 27 with MetaProperty

use of com.haulmont.chile.core.model.MetaProperty in project cuba by cuba-platform.

the class DataManagerBean method writeCrossDataStoreReferences.

protected boolean writeCrossDataStoreReferences(Entity entity, Collection<Entity> allEntities) {
    if (Stores.getAdditional().isEmpty())
        return false;
    boolean repeatRequired = false;
    MetaClass metaClass = metadata.getClassNN(entity.getClass());
    for (MetaProperty property : metaClass.getProperties()) {
        if (property.getRange().isClass() && !property.getRange().getCardinality().isMany()) {
            MetaClass propertyMetaClass = property.getRange().asClass();
            if (!Objects.equals(metadataTools.getStoreName(propertyMetaClass), metadataTools.getStoreName(metaClass))) {
                List<String> relatedProperties = metadataTools.getRelatedProperties(property);
                if (relatedProperties.size() == 0) {
                    continue;
                }
                if (relatedProperties.size() > 1) {
                    log.warn("More than 1 related property is defined for attribute {}, skip handling different data store", property);
                    continue;
                }
                String relatedPropertyName = relatedProperties.get(0);
                if (PersistenceHelper.isLoaded(entity, relatedPropertyName)) {
                    Entity refEntity = entity.getValue(property.getName());
                    if (refEntity == null) {
                        entity.setValue(relatedPropertyName, null);
                    } else {
                        Object refEntityId = refEntity.getId();
                        if (refEntityId instanceof IdProxy) {
                            Object realId = ((IdProxy) refEntityId).get();
                            if (realId == null) {
                                if (allEntities.stream().anyMatch(e -> e.getId().equals(refEntityId))) {
                                    repeatRequired = true;
                                } else {
                                    log.warn("No entity with ID={} in the context, skip handling different data store", refEntityId);
                                }
                            } else {
                                entity.setValue(relatedPropertyName, realId);
                            }
                        } else if (refEntityId instanceof EmbeddableEntity) {
                            MetaProperty relatedProperty = metaClass.getPropertyNN(relatedPropertyName);
                            if (!relatedProperty.getRange().isClass()) {
                                log.warn("PK of entity referenced by {} is a EmbeddableEntity, but related property {} is not", property, relatedProperty);
                            } else {
                                entity.setValue(relatedPropertyName, metadataTools.copy((Entity) refEntityId));
                            }
                        } else {
                            entity.setValue(relatedPropertyName, refEntityId);
                        }
                    }
                }
            }
        }
    }
    return repeatRequired;
}
Also used : MetaClass(com.haulmont.chile.core.model.MetaClass) MetaProperty(com.haulmont.chile.core.model.MetaProperty)

Example 28 with MetaProperty

use of com.haulmont.chile.core.model.MetaProperty in project cuba by cuba-platform.

the class DataServiceQueryBuilder method restrictByPreviousResults.

public void restrictByPreviousResults(UUID sessionId, int queryKey) {
    QueryTransformer transformer = QueryTransformerFactory.createTransformer(queryString);
    MetaClass metaClass = metadata.getClassNN(entityName);
    MetaProperty primaryKey = metadata.getTools().getPrimaryKeyProperty(metaClass);
    if (primaryKey == null)
        throw new IllegalStateException(String.format("Entity %s has no primary key", entityName));
    Class type = primaryKey.getJavaType();
    String entityIdField;
    if (UUID.class.equals(type)) {
        entityIdField = "entityId";
    } else if (Long.class.equals(type)) {
        entityIdField = "longEntityId";
    } else if (Integer.class.equals(type)) {
        entityIdField = "intEntityId";
    } else if (String.class.equals(type)) {
        entityIdField = "stringEntityId";
    } else {
        throw new IllegalStateException(String.format("Unsupported primary key type: %s for %s", type.getSimpleName(), entityName));
    }
    transformer.addJoinAndWhere(", sys$QueryResult _qr", String.format("_qr.%s = {E}.%s and _qr.sessionId = :_qr_sessionId and _qr.queryKey = %s", entityIdField, primaryKey.getName(), queryKey));
    queryString = transformer.getResult();
    this.queryParams.put("_qr_sessionId", sessionId);
}
Also used : MetaClass(com.haulmont.chile.core.model.MetaClass) MetaClass(com.haulmont.chile.core.model.MetaClass) EnumClass(com.haulmont.chile.core.datatypes.impl.EnumClass) MetaProperty(com.haulmont.chile.core.model.MetaProperty)

Example 29 with MetaProperty

use of com.haulmont.chile.core.model.MetaProperty in project cuba by cuba-platform.

the class EntityRestoreServiceBean method restoreDetails.

protected void restoreDetails(Entity entity, Date deleteTs, String storeName) {
    EntityManager em = persistence.getEntityManager(storeName);
    MetaClass metaClass = metadata.getClassNN(entity.getClass());
    List<MetaProperty> properties = new ArrayList<>();
    fillProperties(metaClass, properties, OnDelete.class.getName());
    for (MetaProperty property : properties) {
        OnDelete annotation = property.getAnnotatedElement().getAnnotation(OnDelete.class);
        DeletePolicy deletePolicy = annotation.value();
        if (deletePolicy == DeletePolicy.CASCADE) {
            MetaClass detailMetaClass = property.getRange().asClass();
            if (!storeName.equals(metadata.getTools().getStoreName(detailMetaClass))) {
                log.debug("Cannot restore " + property.getRange().asClass() + " because it is from different data store");
                continue;
            }
            if (!SoftDelete.class.isAssignableFrom(detailMetaClass.getJavaClass())) {
                log.debug("Cannot restore " + property.getRange().asClass() + " because it is hard deleted");
                continue;
            }
            MetaProperty inverseProp = property.getInverse();
            if (inverseProp == null) {
                log.debug("Cannot restore " + property.getRange().asClass() + " because it has no inverse property for " + metaClass);
                continue;
            }
            String jpql = "select e from " + detailMetaClass + " e where e." + inverseProp.getName() + ".id = ?1 " + "and e.deleteTs >= ?2 and e.deleteTs <= ?3";
            Query query = em.createQuery(jpql);
            query.setParameter(1, entity.getId());
            query.setParameter(2, DateUtils.addMilliseconds(deleteTs, -100));
            query.setParameter(3, DateUtils.addMilliseconds(deleteTs, 1000));
            // noinspection unchecked
            List<Entity> list = query.getResultList();
            for (Entity detailEntity : list) {
                if (entity instanceof SoftDelete) {
                    restoreEntity(detailEntity, storeName);
                }
            }
        }
    }
    properties = new ArrayList<>();
    fillProperties(metaClass, properties, OnDeleteInverse.class.getName());
    for (MetaProperty property : properties) {
        OnDeleteInverse annotation = property.getAnnotatedElement().getAnnotation(OnDeleteInverse.class);
        DeletePolicy deletePolicy = annotation.value();
        if (deletePolicy == DeletePolicy.CASCADE) {
            MetaClass detailMetaClass = property.getDomain();
            if (!storeName.equals(metadata.getTools().getStoreName(detailMetaClass))) {
                log.debug("Cannot restore " + property.getRange().asClass() + " because it is from different data store");
                continue;
            }
            if (!SoftDelete.class.isAssignableFrom(detailMetaClass.getJavaClass())) {
                log.debug("Cannot restore " + property.getRange().asClass() + " because it is hard deleted");
                continue;
            }
            List<MetaClass> metClassesToRestore = new ArrayList<>();
            metClassesToRestore.add(detailMetaClass);
            metClassesToRestore.addAll(detailMetaClass.getDescendants());
            for (MetaClass metaClassToRestore : metClassesToRestore) {
                if (!metadata.getTools().isPersistent(metaClassToRestore))
                    continue;
                String jpql = "select e from " + metaClassToRestore.getName() + " e where e." + property.getName() + ".id = ?1 and e.deleteTs >= ?2 and e.deleteTs <= ?3";
                Query query = em.createQuery(jpql);
                query.setParameter(1, entity.getId());
                query.setParameter(2, DateUtils.addMilliseconds(deleteTs, -100));
                query.setParameter(3, DateUtils.addMilliseconds(deleteTs, 1000));
                // noinspection unchecked
                List<Entity> list = query.getResultList();
                for (Entity detailEntity : list) {
                    if (entity instanceof SoftDelete) {
                        restoreEntity(detailEntity, storeName);
                    }
                }
            }
        }
    }
}
Also used : Entity(com.haulmont.cuba.core.entity.Entity) SoftDelete(com.haulmont.cuba.core.entity.SoftDelete) Query(com.haulmont.cuba.core.Query) DeletePolicy(com.haulmont.cuba.core.global.DeletePolicy) EntityManager(com.haulmont.cuba.core.EntityManager) MetaClass(com.haulmont.chile.core.model.MetaClass) OnDeleteInverse(com.haulmont.cuba.core.entity.annotation.OnDeleteInverse) MetaProperty(com.haulmont.chile.core.model.MetaProperty) OnDelete(com.haulmont.cuba.core.entity.annotation.OnDelete)

Example 30 with MetaProperty

use of com.haulmont.chile.core.model.MetaProperty in project cuba by cuba-platform.

the class RdbmsStore method updateReferences.

protected void updateReferences(Entity entity, Entity refEntity, Set<Entity> visited) {
    if (entity == null || refEntity == null || visited.contains(entity))
        return;
    visited.add(entity);
    MetaClass refEntityMetaClass = refEntity.getMetaClass();
    for (MetaProperty property : entity.getMetaClass().getProperties()) {
        if (!property.getRange().isClass() || !property.getRange().asClass().equals(refEntityMetaClass))
            continue;
        if (PersistenceHelper.isLoaded(entity, property.getName())) {
            if (property.getRange().getCardinality().isMany()) {
                Collection collection = entity.getValue(property.getName());
                if (collection != null) {
                    for (Object obj : collection) {
                        updateReferences((Entity) obj, refEntity, visited);
                    }
                }
            } else {
                Entity value = entity.getValue(property.getName());
                if (value != null) {
                    if (value.getId().equals(refEntity.getId())) {
                        if (entity instanceof AbstractInstance) {
                            if (property.isReadOnly() && metadata.getTools().isNotPersistent(property)) {
                                continue;
                            }
                            ((AbstractInstance) entity).setValue(property.getName(), refEntity, false);
                        }
                    } else {
                        updateReferences(value, refEntity, visited);
                    }
                }
            }
        }
    }
}
Also used : AbstractInstance(com.haulmont.chile.core.model.impl.AbstractInstance) MetaClass(com.haulmont.chile.core.model.MetaClass) MetaProperty(com.haulmont.chile.core.model.MetaProperty)

Aggregations

MetaProperty (com.haulmont.chile.core.model.MetaProperty)157 MetaClass (com.haulmont.chile.core.model.MetaClass)102 Entity (com.haulmont.cuba.core.entity.Entity)44 MetaPropertyPath (com.haulmont.chile.core.model.MetaPropertyPath)26 BaseGenericIdEntity (com.haulmont.cuba.core.entity.BaseGenericIdEntity)21 Range (com.haulmont.chile.core.model.Range)13 Nullable (javax.annotation.Nullable)11 CollectionDatasource (com.haulmont.cuba.gui.data.CollectionDatasource)10 CategoryAttribute (com.haulmont.cuba.core.entity.CategoryAttribute)9 java.util (java.util)9 Element (org.dom4j.Element)9 com.haulmont.cuba.core.global (com.haulmont.cuba.core.global)8 Collectors (java.util.stream.Collectors)6 Inject (javax.inject.Inject)6 Query (com.haulmont.cuba.core.Query)5 SoftDelete (com.haulmont.cuba.core.entity.SoftDelete)5 Collection (java.util.Collection)5 MessageTools (com.haulmont.cuba.core.global.MessageTools)4 PropertyDatasource (com.haulmont.cuba.gui.data.PropertyDatasource)4 Logger (org.slf4j.Logger)4