Search in sources :

Example 6 with ExtendedManagedType

use of com.blazebit.persistence.spi.ExtendedManagedType in project blaze-persistence by Blazebit.

the class CachingJpaProvider method isDeleteCascaded.

@Override
public boolean isDeleteCascaded(ManagedType<?> ownerType, String attributeName) {
    ExtendedManagedType managedType = entityMetamodel.getManagedType(ExtendedManagedType.class, ownerType);
    ExtendedAttribute attribute = (ExtendedAttribute) managedType.getAttributes().get(attributeName);
    return attribute != null && attribute.isDeleteCascaded();
}
Also used : ExtendedAttribute(com.blazebit.persistence.spi.ExtendedAttribute) ExtendedManagedType(com.blazebit.persistence.spi.ExtendedManagedType)

Example 7 with ExtendedManagedType

use of com.blazebit.persistence.spi.ExtendedManagedType in project blaze-persistence by Blazebit.

the class ConstantifiedJoinNodeAttributeCollector method visit.

@Override
public void visit(PathExpression expr) {
    PathReference pathReference = expr.getPathReference();
    if (pathReference == null) {
        ((SelectInfo) aliasManager.getAliasInfo(expr.toString())).getExpression().accept(this);
        return;
    }
    JoinNode baseNode = (JoinNode) pathReference.getBaseNode();
    if (pathReference.getField() == null) {
        if (inKey) {
            // We constantify collection as a whole to a single element when reaching this point
            Map<String, Boolean> attributes = new HashMap<>(1);
            attributes.put(KEY_FUNCTION, innerJoin);
            constantifiedJoinNodeAttributes.put(baseNode, attributes);
        } else if (baseNode.getType() instanceof ManagedType<?>) {
            // Here we have a predicate like `d = d2` which is the same as `d.id = d2.id`
            Map<String, Boolean> attributes = constantifiedJoinNodeAttributes.get(baseNode);
            if (attributes == null) {
                attributes = new HashMap<>();
                constantifiedJoinNodeAttributes.put(baseNode, attributes);
            }
            ExtendedManagedType<?> managedType = metamodel.getManagedType(ExtendedManagedType.class, baseNode.getManagedType());
            for (SingularAttribute<?, ?> idAttribute : managedType.getIdAttributes()) {
                addAttribute("", idAttribute, attributes);
            }
        }
        return;
    }
    ExtendedManagedType<?> managedType = metamodel.getManagedType(ExtendedManagedType.class, baseNode.getManagedType());
    ExtendedAttribute<?, ?> extendedAttribute = managedType.getAttribute(pathReference.getField());
    Attribute attr = extendedAttribute.getAttribute();
    // We constantify collection as a whole to a single element when reaching this point
    if (attr instanceof PluralAttribute<?, ?, ?>) {
        if (inKey) {
            Map<String, Boolean> attributes = new HashMap<>(1);
            attributes.put(KEY_FUNCTION, innerJoin);
            constantifiedJoinNodeAttributes.put(baseNode, attributes);
        }
        return;
    }
    int dotIndex = expr.getField().lastIndexOf('.');
    SingularAttribute<?, ?> singularAttr = (SingularAttribute<?, ?>) attr;
    String associationName = getSingleValuedIdAccessAssociationName(pathReference.getField(), extendedAttribute);
    Object baseNodeKey;
    String prefix;
    if (associationName == null) {
        baseNodeKey = baseNode;
        prefix = attr.getDeclaringType() instanceof EmbeddableType<?> ? pathReference.getField().substring(0, dotIndex + 1) : "";
    } else {
        baseNodeKey = new AbstractMap.SimpleEntry<>(baseNode, associationName);
        if (attr.getDeclaringType() instanceof EmbeddableType<?>) {
            prefix = pathReference.getField().substring(associationName.length() + 1, dotIndex + 1);
        } else {
            prefix = "";
        }
    }
    Map<String, Boolean> attributes = constantifiedJoinNodeAttributes.get(baseNodeKey);
    if (attributes == null) {
        attributes = new HashMap<>();
        constantifiedJoinNodeAttributes.put(baseNodeKey, attributes);
    }
    addAttribute(prefix, singularAttr, attributes);
    StringBuilder attributeNameBuilder = null;
    Map<String, Boolean> baseNodeAttributes = null;
    String associationNamePrefix = associationName == null ? "" : associationName + '.';
    // Also add all attributes to the set that resolve to the same column names i.e. which are essentially equivalent
    Map<String, Boolean> newAttributes = new HashMap<>();
    for (Map.Entry<String, Boolean> entry : attributes.entrySet()) {
        String attribute = entry.getKey();
        if (attribute != KEY_FUNCTION) {
            for (ExtendedAttribute<?, ?> columnEquivalentAttribute : managedType.getAttribute(associationNamePrefix + attribute).getColumnEquivalentAttributes()) {
                List<Attribute<?, ?>> attributePath = columnEquivalentAttribute.getAttributePath();
                String attributeName;
                if (attributePath.size() == 1) {
                    attributeName = attributePath.get(0).getName();
                } else {
                    if (attributeNameBuilder == null) {
                        attributeNameBuilder = new StringBuilder();
                    } else {
                        attributeNameBuilder.setLength(0);
                    }
                    attributeNameBuilder.append(attributePath.get(0).getName());
                    for (int i = 1; i < attributePath.size(); i++) {
                        attributeNameBuilder.append('.');
                        attributeNameBuilder.append(attributePath.get(i).getName());
                    }
                    attributeName = attributeNameBuilder.toString();
                }
                // Be careful with single valued association ids, they have a different baseNodeKey
                if (!associationNamePrefix.isEmpty() && !attributeName.startsWith(associationNamePrefix)) {
                    if (baseNodeAttributes == null) {
                        baseNodeAttributes = constantifiedJoinNodeAttributes.get(baseNode);
                        if (baseNodeAttributes == null) {
                            baseNodeAttributes = new HashMap<>();
                            constantifiedJoinNodeAttributes.put(baseNode, baseNodeAttributes);
                        }
                    }
                    baseNodeAttributes.put(attributeName, entry.getValue());
                } else {
                    newAttributes.put(attributeName, entry.getValue());
                }
            }
        }
    }
    attributes.putAll(newAttributes);
}
Also used : PathReference(com.blazebit.persistence.parser.expression.PathReference) IdentityHashMap(java.util.IdentityHashMap) HashMap(java.util.HashMap) SingularAttribute(javax.persistence.metamodel.SingularAttribute) Attribute(javax.persistence.metamodel.Attribute) ExtendedAttribute(com.blazebit.persistence.spi.ExtendedAttribute) PluralAttribute(javax.persistence.metamodel.PluralAttribute) PluralAttribute(javax.persistence.metamodel.PluralAttribute) ExtendedManagedType(com.blazebit.persistence.spi.ExtendedManagedType) EmbeddableType(javax.persistence.metamodel.EmbeddableType) AbstractMap(java.util.AbstractMap) SingularAttribute(javax.persistence.metamodel.SingularAttribute) Map(java.util.Map) IdentityHashMap(java.util.IdentityHashMap) HashMap(java.util.HashMap) AbstractMap(java.util.AbstractMap)

Example 8 with ExtendedManagedType

use of com.blazebit.persistence.spi.ExtendedManagedType in project blaze-persistence by Blazebit.

the class EntityViewUpdaterImpl method createSingularAttributeFlusher.

private DirtyAttributeFlusher<?, ?, ?> createSingularAttributeFlusher(EntityViewManagerImpl evm, Map<Object, EntityViewUpdaterImpl> localCache, ManagedViewTypeImplementor<?> viewType, AbstractMethodAttribute<?, ?> attribute, EntityViewUpdaterImpl owner, String ownerMapping) {
    EntityMetamodel entityMetamodel = evm.getMetamodel().getEntityMetamodel();
    Class<?> entityClass = viewType.getEntityClass();
    String attributeName = attribute.getName();
    String attributeMapping = attribute.getMapping();
    AttributeAccessor entityAttributeAccessor = Accessors.forEntityMapping(evm, attribute);
    String attributeLocation = attribute.getLocation();
    boolean cascadePersist = attribute.isPersistCascaded();
    boolean cascadeUpdate = attribute.isUpdateCascaded();
    boolean cascadeDelete = attribute.isDeleteCascaded();
    boolean viewOnlyDeleteCascaded = cascadeDelete && !entityMetamodel.getManagedType(ExtendedManagedType.class, entityClass).getAttribute(attributeMapping).isDeleteCascaded();
    boolean optimisticLockProtected = attribute.isOptimisticLockProtected();
    Set<Type<?>> readOnlyAllowedSubtypes = attribute.getReadOnlyAllowedSubtypes();
    Set<Type<?>> persistAllowedSubtypes = attribute.getPersistCascadeAllowedSubtypes();
    Set<Type<?>> updateAllowedSubtypes = attribute.getUpdateCascadeAllowedSubtypes();
    JpaProvider jpaProvider = evm.getJpaProvider();
    if (attribute.isSubview()) {
        boolean shouldFlushUpdates = cascadeUpdate && !updateAllowedSubtypes.isEmpty();
        boolean shouldFlushPersists = cascadePersist && !persistAllowedSubtypes.isEmpty();
        ManagedViewTypeImplementor<?> subviewType = (ManagedViewTypeImplementor<?>) ((com.blazebit.persistence.view.metamodel.SingularAttribute<?, ?>) attribute).getType();
        boolean passThrough = false;
        if (attribute.isUpdatable() || shouldFlushUpdates || (passThrough = shouldPassThrough(evm, viewType, attribute))) {
            // TODO: shouldn't this be done for any flat view? or are updatable flat views for entity types disallowed?
            if (!(subviewType.getJpaManagedType() instanceof EntityType<?>)) {
                AttributeAccessor viewAttributeAccessor = Accessors.forViewAttribute(evm, attribute, true);
                // A singular attribute where the subview refers to an embeddable type
                EmbeddableUpdaterBasedViewToEntityMapper viewToEntityMapper = new EmbeddableUpdaterBasedViewToEntityMapper(attributeLocation, evm, subviewType.getJavaType(), readOnlyAllowedSubtypes, persistAllowedSubtypes, updateAllowedSubtypes, EntityLoaders.referenceLoaderForAttribute(evm, localCache, subviewType, attribute), shouldFlushPersists, null, owner == null ? this : owner, ownerMapping == null ? attributeMapping : ownerMapping + "." + attributeMapping, localCache);
                CompositeAttributeFlusher nestedFlusher = (CompositeAttributeFlusher) viewToEntityMapper.getFullGraphNode();
                boolean supportsQueryFlush = nestedFlusher.supportsQueryFlush() && jpaProvider.supportsUpdateSetEmbeddable();
                String parameterName;
                String updateFragment;
                if (supportsQueryFlush) {
                    parameterName = attributeName;
                    updateFragment = attributeMapping;
                } else {
                    parameterName = attributeName + "_";
                    updateFragment = attributeMapping + ".";
                }
                return new EmbeddableAttributeFlusher<>(attributeName, attributeMapping, updateFragment, parameterName, optimisticLockProtected, passThrough, supportsQueryFlush, entityAttributeAccessor, viewAttributeAccessor, viewToEntityMapper);
            } else {
                // Subview refers to entity type
                ViewTypeImplementor<?> attributeViewType = (ViewTypeImplementor<?>) subviewType;
                InitialValueAttributeAccessor viewAttributeAccessor = Accessors.forMutableViewAttribute(evm, attribute);
                AttributeAccessor subviewIdAccessor;
                InverseFlusher<Object> inverseFlusher = InverseFlusher.forAttribute(evm, localCache, viewType, attribute, TypeDescriptor.forType(evm, localCache, this, attribute, subviewType, owner, ownerMapping), owner, ownerMapping);
                InverseRemoveStrategy inverseRemoveStrategy = attribute.getInverseRemoveStrategy();
                ManagedType<?> ownerEntityType = owner == null ? viewType.getJpaManagedType() : owner.managedViewType.getJpaManagedType();
                ViewToEntityMapper viewToEntityMapper;
                boolean fetch = shouldFlushUpdates;
                String parameterName = null;
                String attributeElementIdMapping;
                if (ownerEntityType instanceof EntityType<?> && attribute.getMapping() != null) {
                    ExtendedManagedType<?> extendedManagedType = evm.getMetamodel().getEntityMetamodel().getManagedType(ExtendedManagedType.class, attributeViewType.getEntityClass());
                    attributeElementIdMapping = TypeDescriptor.getAttributeElementIdentifier(evm, (EntityType<?>) ownerEntityType, attribute.getName(), ownerMapping, attribute.getMapping(), extendedManagedType.getType());
                } else {
                    attributeElementIdMapping = ((MappingAttribute<?, ?>) attributeViewType.getIdAttribute()).getMapping();
                }
                subviewIdAccessor = Accessors.forSubviewAssociationId(evm, attributeViewType, attributeElementIdMapping, true);
                Attribute<?, ?> attributeIdAttribute = attributeViewType.getJpaManagedType().getAttribute(attributeElementIdMapping);
                javax.persistence.metamodel.Type<?> attributeIdAttributeType = entityMetamodel.type(JpaMetamodelUtils.resolveFieldClass(attributeViewType.getEntityClass(), attributeIdAttribute));
                List<String> idComponentMappings;
                boolean requiresComponentWiseSetInUpdate = true;
                if (requiresComponentWiseSetInUpdate && attributeIdAttributeType instanceof EmbeddableType<?>) {
                    // If the identifier used for the association is an embeddable, we must collect the individual attribute components since updates don't work on embeddables directly
                    Set<Attribute<?, ?>> idAttributeComponents = (Set<Attribute<?, ?>>) ((EmbeddableType<?>) attributeIdAttributeType).getAttributes();
                    idComponentMappings = new ArrayList<>(idAttributeComponents.size());
                    for (Attribute<?, ?> idAttributeComponent : idAttributeComponents) {
                        idComponentMappings.add(attributeMapping + "." + attributeElementIdMapping + "." + idAttributeComponent.getName());
                    }
                } else {
                    idComponentMappings = Collections.singletonList(attributeMapping + "." + attributeElementIdMapping);
                }
                String[] idAttributeMappings = idComponentMappings.toArray(new String[idComponentMappings.size()]);
                if (attribute.isUpdatable() && ownerEntityType instanceof EntityType<?>) {
                    viewToEntityMapper = createViewToEntityMapper(attributeLocation, evm, localCache, (EntityType<?>) ownerEntityType, attributeName, attributeMapping, attributeViewType, cascadePersist, cascadeUpdate, readOnlyAllowedSubtypes, persistAllowedSubtypes, updateAllowedSubtypes, EntityLoaders.referenceLoaderForAttribute(evm, localCache, attributeViewType, attribute.getViewTypes(), attributeElementIdMapping), owner, ownerMapping);
                    parameterName = attributeName;
                } else {
                    String elementIdentifier;
                    if (ownerEntityType instanceof EntityType<?>) {
                        elementIdentifier = TypeDescriptor.getAttributeElementIdentifier(evm, (EntityType<?>) ownerEntityType, attributeName, ownerMapping, attributeMapping, attributeViewType.getJpaManagedType());
                    } else {
                        elementIdentifier = null;
                    }
                    AttributeAccessor entityIdAccessor = Accessors.forEntityMapping(evm, attributeViewType.getEntityClass(), elementIdentifier);
                    if (shouldFlushUpdates) {
                        viewToEntityMapper = new UpdaterBasedViewToEntityMapper(attributeLocation, evm, subviewType.getJavaType(), readOnlyAllowedSubtypes, persistAllowedSubtypes, updateAllowedSubtypes, EntityLoaders.referenceLoaderForAttribute(evm, localCache, subviewType, attribute), subviewIdAccessor, entityIdAccessor, shouldFlushPersists, owner, ownerMapping, localCache);
                    } else if (!shouldFlushPersists && shouldPassThrough(evm, viewType, attribute)) {
                        viewToEntityMapper = new LoadOnlyViewToEntityMapper(EntityLoaders.referenceLoaderForAttribute(evm, localCache, subviewType, attribute), subviewIdAccessor, entityIdAccessor);
                    } else {
                        viewToEntityMapper = new LoadOrPersistViewToEntityMapper(attributeLocation, evm, subviewType.getJavaType(), readOnlyAllowedSubtypes, persistAllowedSubtypes, updateAllowedSubtypes, EntityLoaders.referenceLoaderForAttribute(evm, localCache, subviewType, attribute), subviewIdAccessor, entityIdAccessor, shouldFlushPersists, owner, ownerMapping, localCache);
                    }
                }
                return new SubviewAttributeFlusher<>(attributeName, attributeMapping, optimisticLockProtected, attribute.isUpdatable(), cascadeDelete, attribute.isOrphanRemoval(), viewOnlyDeleteCascaded, subviewType.getConverter(), fetch, idAttributeMappings, parameterName, passThrough, owner != null, entityAttributeAccessor, viewAttributeAccessor, subviewIdAccessor, viewToEntityMapper, inverseFlusher, inverseRemoveStrategy);
            }
        } else {
            return null;
        }
    } else {
        BasicTypeImpl<?> attributeType = (BasicTypeImpl<?>) ((com.blazebit.persistence.view.metamodel.SingularAttribute<?, ?>) attribute).getType();
        TypeDescriptor elementDescriptor = TypeDescriptor.forType(evm, localCache, this, attribute, attributeType, owner, ownerMapping);
        // Basic attributes like String, Integer but also JPA managed types
        boolean updatable = attribute.isUpdatable();
        if (updatable || elementDescriptor.shouldFlushMutations() || shouldPassThrough(evm, viewType, attribute)) {
            // Basic attributes can normally be updated by queries
            InverseFlusher<Object> inverseFlusher = InverseFlusher.forAttribute(evm, localCache, viewType, attribute, elementDescriptor, owner, ownerMapping);
            InverseRemoveStrategy inverseRemoveStrategy = attribute.getInverseRemoveStrategy();
            String parameterName = attributeName;
            String updateFragment = attributeMapping;
            ManagedType<?> ownerEntityType = owner == null ? viewType.getJpaManagedType() : owner.managedViewType.getJpaManagedType();
            UnmappedBasicAttributeCascadeDeleter deleter;
            if (elementDescriptor.isJpaEntity() && cascadeDelete && ownerEntityType instanceof EntityType<?>) {
                String elementIdAttributeName = TypeDescriptor.getAttributeElementIdentifier(evm, (EntityType<?>) ownerEntityType, attributeName, ownerMapping, attributeMapping, attributeType.getManagedType());
                deleter = new UnmappedBasicAttributeCascadeDeleter(evm, attributeName, entityMetamodel.getManagedType(ExtendedManagedType.class, entityClass).getAttribute(attributeMapping), attributeMapping + "." + elementIdAttributeName, false);
            } else {
                deleter = null;
            }
            // When wanting to read the actual value of non-updatable attributes or writing values to attributes we need the view attribute accessor
            // Whenever we merge or persist, we are going to need that
            AttributeAccessor viewAttributeAccessor;
            if (elementDescriptor.shouldFlushMutations()) {
                viewAttributeAccessor = Accessors.forMutableViewAttribute(evm, attribute);
            } else {
                viewAttributeAccessor = Accessors.forViewAttribute(evm, attribute, true);
            }
            Map.Entry<AttributeAccessor, BasicAttributeFlusher>[] componentFlusherEntries = null;
            if (elementDescriptor.isJpaEmbeddable()) {
                if (!jpaProvider.supportsUpdateSetEmbeddable()) {
                    Set<Attribute<?, ?>> attributes = (Set<Attribute<?, ?>>) attributeType.getManagedType().getAttributes();
                    Map<AttributeAccessor, BasicAttributeFlusher> componentFlushers = new HashMap<>(attributes.size());
                    buildComponentFlushers(evm, viewType.getEntityClass(), attributeType.getJavaType(), attributeName + "_", attributeMapping + ".", "", attributes, componentFlushers);
                    componentFlusherEntries = componentFlushers.entrySet().toArray(new Map.Entry[componentFlushers.size()]);
                }
            }
            return new BasicAttributeFlusher<>(attributeName, attributeMapping, true, optimisticLockProtected, updatable, cascadeDelete, attribute.isOrphanRemoval(), viewOnlyDeleteCascaded, componentFlusherEntries, elementDescriptor, updateFragment, parameterName, entityAttributeAccessor, viewAttributeAccessor, deleter, inverseFlusher, inverseRemoveStrategy);
        } else {
            return null;
        }
    }
}
Also used : CompositeAttributeFlusher(com.blazebit.persistence.view.impl.update.flush.CompositeAttributeFlusher) ViewTypeImplementor(com.blazebit.persistence.view.impl.metamodel.ViewTypeImplementor) ManagedViewTypeImplementor(com.blazebit.persistence.view.impl.metamodel.ManagedViewTypeImplementor) HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap) InverseRemoveStrategy(com.blazebit.persistence.view.InverseRemoveStrategy) SubviewAttributeFlusher(com.blazebit.persistence.view.impl.update.flush.SubviewAttributeFlusher) UnmappedBasicAttributeCascadeDeleter(com.blazebit.persistence.view.impl.update.flush.UnmappedBasicAttributeCascadeDeleter) ExtendedManagedType(com.blazebit.persistence.spi.ExtendedManagedType) EntityType(javax.persistence.metamodel.EntityType) TypeDescriptor(com.blazebit.persistence.view.impl.update.flush.TypeDescriptor) InitialValueAttributeAccessor(com.blazebit.persistence.view.impl.accessor.InitialValueAttributeAccessor) AttributeAccessor(com.blazebit.persistence.view.impl.accessor.AttributeAccessor) EmbeddableUpdaterBasedViewToEntityMapper(com.blazebit.persistence.view.impl.entity.EmbeddableUpdaterBasedViewToEntityMapper) LoadOrPersistViewToEntityMapper(com.blazebit.persistence.view.impl.entity.LoadOrPersistViewToEntityMapper) Set(java.util.Set) HashSet(java.util.HashSet) UpdaterBasedViewToEntityMapper(com.blazebit.persistence.view.impl.entity.UpdaterBasedViewToEntityMapper) EmbeddableUpdaterBasedViewToEntityMapper(com.blazebit.persistence.view.impl.entity.EmbeddableUpdaterBasedViewToEntityMapper) LoadOnlyViewToEntityMapper(com.blazebit.persistence.view.impl.entity.LoadOnlyViewToEntityMapper) MappingAttribute(com.blazebit.persistence.view.metamodel.MappingAttribute) SingularAttribute(javax.persistence.metamodel.SingularAttribute) Attribute(javax.persistence.metamodel.Attribute) AbstractMethodAttribute(com.blazebit.persistence.view.impl.metamodel.AbstractMethodAttribute) PluralAttribute(com.blazebit.persistence.view.metamodel.PluralAttribute) ExtendedAttribute(com.blazebit.persistence.spi.ExtendedAttribute) MapAttribute(com.blazebit.persistence.view.metamodel.MapAttribute) MethodAttribute(com.blazebit.persistence.view.metamodel.MethodAttribute) BasicTypeImpl(com.blazebit.persistence.view.impl.metamodel.BasicTypeImpl) InitialValueAttributeAccessor(com.blazebit.persistence.view.impl.accessor.InitialValueAttributeAccessor) EmbeddableAttributeFlusher(com.blazebit.persistence.view.impl.update.flush.EmbeddableAttributeFlusher) LoadOrPersistViewToEntityMapper(com.blazebit.persistence.view.impl.entity.LoadOrPersistViewToEntityMapper) LoadOnlyViewToEntityMapper(com.blazebit.persistence.view.impl.entity.LoadOnlyViewToEntityMapper) SimpleMapViewToEntityMapper(com.blazebit.persistence.view.impl.update.flush.SimpleMapViewToEntityMapper) UpdaterBasedViewToEntityMapper(com.blazebit.persistence.view.impl.entity.UpdaterBasedViewToEntityMapper) EmbeddableUpdaterBasedViewToEntityMapper(com.blazebit.persistence.view.impl.entity.EmbeddableUpdaterBasedViewToEntityMapper) MapViewToEntityMapper(com.blazebit.persistence.view.impl.entity.MapViewToEntityMapper) ViewToEntityMapper(com.blazebit.persistence.view.impl.entity.ViewToEntityMapper) JpaProvider(com.blazebit.persistence.spi.JpaProvider) ManagedViewTypeImplementor(com.blazebit.persistence.view.impl.metamodel.ManagedViewTypeImplementor) ManagedType(javax.persistence.metamodel.ManagedType) BasicType(com.blazebit.persistence.view.metamodel.BasicType) EntityType(javax.persistence.metamodel.EntityType) Type(com.blazebit.persistence.view.metamodel.Type) ExtendedManagedType(com.blazebit.persistence.spi.ExtendedManagedType) VersionBasicUserType(com.blazebit.persistence.view.spi.type.VersionBasicUserType) ManagedViewType(com.blazebit.persistence.view.metamodel.ManagedViewType) EmbeddableType(javax.persistence.metamodel.EmbeddableType) ViewType(com.blazebit.persistence.view.metamodel.ViewType) BasicAttributeFlusher(com.blazebit.persistence.view.impl.update.flush.BasicAttributeFlusher) EntityMetamodel(com.blazebit.persistence.parser.EntityMetamodel)

Example 9 with ExtendedManagedType

use of com.blazebit.persistence.spi.ExtendedManagedType in project blaze-persistence by Blazebit.

the class EntityViewUpdaterImpl method createPluralAttributeFlusher.

private DirtyAttributeFlusher<?, ?, ?> createPluralAttributeFlusher(EntityViewManagerImpl evm, Map<Object, EntityViewUpdaterImpl> localCache, ManagedViewTypeImplementor<?> viewType, String idAttributeName, FlushStrategy flushStrategy, AbstractMethodAttribute<?, ?> attribute, DirtyAttributeFlusher<?, ?, ?> ownerIdFlusher, EntityViewUpdaterImpl owner, String ownerMapping) {
    EntityMetamodel entityMetamodel = evm.getMetamodel().getEntityMetamodel();
    Class<?> entityClass = viewType.getEntityClass();
    ExtendedManagedType managedType = entityMetamodel.getManagedType(ExtendedManagedType.class, entityClass);
    String attributeName = attribute.getName();
    String attributeMapping = attribute.getMapping();
    AttributeAccessor entityAttributeAccessor = Accessors.forEntityMapping(evm, attribute);
    boolean cascadeDelete = attribute.isDeleteCascaded();
    boolean viewOnlyDeleteCascaded = cascadeDelete && !managedType.getAttribute(attributeMapping).isDeleteCascaded();
    boolean optimisticLockProtected = attribute.isOptimisticLockProtected();
    JpaProvider jpaProvider = evm.getJpaProvider();
    PluralAttribute<?, ?, ?> pluralAttribute = (PluralAttribute<?, ?, ?>) attribute;
    InitialValueAttributeAccessor viewAttributeAccessor = Accessors.forMutableViewAttribute(evm, attribute);
    ManagedType<?> ownerManagedType = owner == null ? viewType.getJpaManagedType() : owner.managedViewType.getJpaManagedType();
    EntityType<?> ownerEntityType = ownerManagedType instanceof EntityType<?> ? (EntityType<?>) ownerManagedType : null;
    DirtyAttributeFlusher<?, ?, ?> attributeOwnerFlusher;
    if (attributeMapping == null || ownerEntityType == null) {
        // In case of cascading only attributes i.e. correlations, we use the owner id flusher as it's not updatable anyway
        attributeOwnerFlusher = ownerIdFlusher;
    } else {
        Map<String, String> joinTableOwnerProperties;
        if (ownerMapping == null) {
            joinTableOwnerProperties = jpaProvider.getJoinMappingPropertyNames(ownerEntityType, ownerMapping, attributeMapping);
        } else {
            joinTableOwnerProperties = jpaProvider.getJoinMappingPropertyNames(ownerEntityType, ownerMapping, ownerMapping + "." + attributeMapping);
        }
        if (joinTableOwnerProperties.size() != 1) {
            String idMapping = ownerIdFlusher.getMapping();
            String prefix;
            if (idMapping.endsWith(".")) {
                prefix = idMapping;
            } else {
                prefix = idMapping + ".";
            }
            for (String joinTableOwnerProperty : joinTableOwnerProperties.keySet()) {
                if (!joinTableOwnerProperty.startsWith(prefix)) {
                    throw new IllegalArgumentException("Multiple joinable owner properties for attribute '" + attributeName + "' of " + ownerEntityType.getJavaType().getName() + " found which is not yet supported. Consider using the primary key instead!");
                }
            }
            attributeOwnerFlusher = ownerIdFlusher;
        } else if (ownerIdFlusher.getMapping().equals(joinTableOwnerProperties.values().iterator().next())) {
            attributeOwnerFlusher = ownerIdFlusher;
        } else {
            attributeOwnerFlusher = findSingularAttributeFlusherByMapping(evm, localCache, owner, viewType, attributeName, joinTableOwnerProperties.keySet().iterator().next());
        }
    }
    TypeDescriptor elementDescriptor = TypeDescriptor.forType(evm, localCache, this, attribute, pluralAttribute.getElementType(), owner, ownerMapping);
    boolean collectionUpdatable = attribute.isUpdatable();
    CollectionRemoveListener elementRemoveListener = createOrphanRemoveListener(attribute, elementDescriptor);
    CollectionRemoveListener elementCascadeDeleteListener = createCascadeDeleteListener(attribute, elementDescriptor);
    boolean jpaProviderDeletesCollection;
    boolean supportsCollectionDml = jpaProvider.supportsInsertStatement();
    if (elementDescriptor.getAttributeIdAttributeName() != null) {
        jpaProviderDeletesCollection = jpaProvider.supportsJoinTableCleanupOnDelete();
    } else {
        jpaProviderDeletesCollection = jpaProvider.supportsCollectionTableCleanupOnDelete();
    }
    if (attribute instanceof MapAttribute<?, ?, ?>) {
        MapAttribute<?, ?, ?> mapAttribute = (MapAttribute<?, ?, ?>) attribute;
        TypeDescriptor keyDescriptor = TypeDescriptor.forType(evm, localCache, this, attribute, mapAttribute.getKeyType(), owner, ownerMapping);
        // TODO: currently there is no possibility to set this
        CollectionRemoveListener keyRemoveListener = null;
        CollectionRemoveListener keyCascadeDeleteListener = null;
        if (collectionUpdatable || keyDescriptor.shouldFlushMutations() || elementDescriptor.shouldFlushMutations() || shouldPassThrough(evm, viewType, attribute)) {
            MapViewToEntityMapper mapper = new SimpleMapViewToEntityMapper(keyDescriptor.getViewToEntityMapper(), elementDescriptor.getViewToEntityMapper());
            MapViewToEntityMapper loadOnlyMapper = new SimpleMapViewToEntityMapper(keyDescriptor.getLoadOnlyViewToEntityMapper(), elementDescriptor.getLoadOnlyViewToEntityMapper());
            MapInstantiatorImplementor<?, ?> mapInstantiator = attribute.getMapInstantiator();
            return new MapAttributeFlusher<Object, RecordingMap<Map<?, ?>, ?, ?>>(attributeName, attributeMapping, owner == null ? entityClass : owner.fullEntityLoader.getEntityClass(), idAttributeName, ownerMapping, attributeOwnerFlusher, createPluralAttributeSubFlusher(evm, localCache, viewType, attribute, "element", mapAttribute.getElementType(), owner, ownerMapping), supportsCollectionDml, flushStrategy, entityAttributeAccessor, viewAttributeAccessor, optimisticLockProtected, collectionUpdatable, keyCascadeDeleteListener, elementCascadeDeleteListener, keyRemoveListener, elementRemoveListener, viewOnlyDeleteCascaded, jpaProviderDeletesCollection, keyDescriptor, elementDescriptor, mapper, loadOnlyMapper, mapInstantiator);
        } else {
            return null;
        }
    } else {
        if (collectionUpdatable || elementDescriptor.shouldFlushMutations() || shouldPassThrough(evm, viewType, attribute)) {
            InverseFlusher<Object> inverseFlusher = InverseFlusher.forAttribute(evm, localCache, viewType, attribute, elementDescriptor, owner, ownerMapping);
            InverseRemoveStrategy inverseRemoveStrategy = attribute.getInverseRemoveStrategy();
            CollectionInstantiatorImplementor<?, ?> collectionInstantiator = attribute.getCollectionInstantiator();
            if (pluralAttribute.isIndexed()) {
                return new IndexedListAttributeFlusher<Object, RecordingList<List<?>>>(attributeName, attributeMapping, owner == null ? entityClass : owner.fullEntityLoader.getEntityClass(), idAttributeName, ownerMapping, attributeOwnerFlusher, createPluralAttributeSubFlusher(evm, localCache, viewType, attribute, "element", pluralAttribute.getElementType(), owner, ownerMapping), supportsCollectionDml, flushStrategy, entityAttributeAccessor, viewAttributeAccessor, optimisticLockProtected, collectionUpdatable, viewOnlyDeleteCascaded, jpaProviderDeletesCollection, elementCascadeDeleteListener, elementRemoveListener, collectionInstantiator, elementDescriptor, inverseFlusher, inverseRemoveStrategy);
            } else {
                return new CollectionAttributeFlusher(attributeName, attributeMapping, owner == null ? entityClass : owner.fullEntityLoader.getEntityClass(), idAttributeName, ownerMapping, attributeOwnerFlusher, createPluralAttributeSubFlusher(evm, localCache, viewType, attribute, "element", pluralAttribute.getElementType(), owner, ownerMapping), supportsCollectionDml, flushStrategy, entityAttributeAccessor, viewAttributeAccessor, optimisticLockProtected, collectionUpdatable, viewOnlyDeleteCascaded, jpaProviderDeletesCollection, elementCascadeDeleteListener, elementRemoveListener, collectionInstantiator, elementDescriptor, inverseFlusher, inverseRemoveStrategy);
            }
        } else {
            return null;
        }
    }
}
Also used : InitialValueAttributeAccessor(com.blazebit.persistence.view.impl.accessor.InitialValueAttributeAccessor) MapAttributeFlusher(com.blazebit.persistence.view.impl.update.flush.MapAttributeFlusher) InverseRemoveStrategy(com.blazebit.persistence.view.InverseRemoveStrategy) CollectionRemoveListener(com.blazebit.persistence.view.impl.collection.CollectionRemoveListener) ViewCollectionRemoveListener(com.blazebit.persistence.view.impl.update.flush.ViewCollectionRemoveListener) EntityCollectionRemoveListener(com.blazebit.persistence.view.impl.update.flush.EntityCollectionRemoveListener) IndexedListAttributeFlusher(com.blazebit.persistence.view.impl.update.flush.IndexedListAttributeFlusher) List(java.util.List) RecordingList(com.blazebit.persistence.view.impl.collection.RecordingList) ArrayList(java.util.ArrayList) CollectionAttributeFlusher(com.blazebit.persistence.view.impl.update.flush.CollectionAttributeFlusher) JpaProvider(com.blazebit.persistence.spi.JpaProvider) PluralAttribute(com.blazebit.persistence.view.metamodel.PluralAttribute) ExtendedManagedType(com.blazebit.persistence.spi.ExtendedManagedType) MapAttribute(com.blazebit.persistence.view.metamodel.MapAttribute) TypeDescriptor(com.blazebit.persistence.view.impl.update.flush.TypeDescriptor) SimpleMapViewToEntityMapper(com.blazebit.persistence.view.impl.update.flush.SimpleMapViewToEntityMapper) MapViewToEntityMapper(com.blazebit.persistence.view.impl.entity.MapViewToEntityMapper) InitialValueAttributeAccessor(com.blazebit.persistence.view.impl.accessor.InitialValueAttributeAccessor) AttributeAccessor(com.blazebit.persistence.view.impl.accessor.AttributeAccessor) SimpleMapViewToEntityMapper(com.blazebit.persistence.view.impl.update.flush.SimpleMapViewToEntityMapper) EntityMetamodel(com.blazebit.persistence.parser.EntityMetamodel) Map(java.util.Map) RecordingMap(com.blazebit.persistence.view.impl.collection.RecordingMap) HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap) TreeMap(java.util.TreeMap)

Example 10 with ExtendedManagedType

use of com.blazebit.persistence.spi.ExtendedManagedType in project blaze-persistence by Blazebit.

the class AbstractCommonQueryBuilder method fromValues.

public BuilderType fromValues(Class<?> valueClass, String alias, int valueCount) {
    ManagedType<?> type = mainQuery.metamodel.getManagedType(valueClass);
    if (type == null) {
        String sqlType = mainQuery.dbmsDialect.getSqlType(valueClass);
        if (sqlType == null) {
            throw new IllegalArgumentException("The basic type " + valueClass.getSimpleName() + " has no column type registered in the DbmsDialect '" + mainQuery.dbmsDialect.getClass().getName() + "'! Register a column type or consider using the fromValues variant that extracts column types from entity attributes!");
        }
        String typeName = cbf.getNamedTypes().get(valueClass);
        if (typeName == null) {
            throw new IllegalArgumentException("Unsupported non-managed type for VALUES clause: " + valueClass.getName() + ". You can register the type via com.blazebit.persistence.spi.CriteriaBuilderConfiguration.registerNamedType. Please report this so that we can add the type definition as well!");
        }
        String castedParameter = mainQuery.dbmsDialect.cast("?", sqlType);
        ExtendedAttribute valuesLikeAttribute = mainQuery.metamodel.getManagedType(ExtendedManagedType.class, ValuesEntity.class).getAttribute("value");
        prepareFromModification();
        joinManager.addRootValues(ValuesEntity.class, valueClass, alias, valueCount, typeName, castedParameter, false, true, "value", valuesLikeAttribute, null, null);
    } else if (type instanceof EntityType<?>) {
        prepareFromModification();
        joinManager.addRootValues(valueClass, valueClass, alias, valueCount, null, null, false, true, null, null, null, null);
    } else {
        ExtendedManagedType<?> extendedManagedType = mainQuery.metamodel.getManagedType(ExtendedManagedType.class, valueClass);
        Map.Entry<? extends EntityType<?>, String> entry = extendedManagedType.getEmbeddableSingularOwner();
        boolean singular = true;
        if (entry == null) {
            singular = false;
            entry = extendedManagedType.getEmbeddablePluralOwner();
        }
        if (entry == null) {
            throw new IllegalArgumentException("Unsupported use of embeddable type [" + valueClass + "] for values clause! Use the entity type and fromIdentifiableValues instead or introduce a CTE entity containing just the embeddable to be able to query it!");
        }
        Class<?> valueHolderEntityClass = entry.getKey().getJavaType();
        String valuesLikeAttributeName = entry.getValue();
        ExtendedAttribute valuesLikeAttribute = mainQuery.metamodel.getManagedType(ExtendedManagedType.class, valueHolderEntityClass).getAttribute(valuesLikeAttributeName);
        prepareFromModification();
        joinManager.addRootValues(valueHolderEntityClass, valueClass, alias, valueCount, null, null, false, singular, valuesLikeAttributeName, valuesLikeAttribute, null, null);
    }
    fromClassExplicitlySet = true;
    return (BuilderType) this;
}
Also used : EntityType(javax.persistence.metamodel.EntityType) ExtendedAttribute(com.blazebit.persistence.spi.ExtendedAttribute) ValuesEntity(com.blazebit.persistence.impl.function.entity.ValuesEntity) ExtendedManagedType(com.blazebit.persistence.spi.ExtendedManagedType)

Aggregations

ExtendedManagedType (com.blazebit.persistence.spi.ExtendedManagedType)20 ExtendedAttribute (com.blazebit.persistence.spi.ExtendedAttribute)13 EntityType (javax.persistence.metamodel.EntityType)8 PathExpression (com.blazebit.persistence.parser.expression.PathExpression)7 ManagedType (javax.persistence.metamodel.ManagedType)7 HashMap (java.util.HashMap)6 Map (java.util.Map)6 EntityMetamodel (com.blazebit.persistence.parser.EntityMetamodel)5 ArrayList (java.util.ArrayList)4 Attribute (javax.persistence.metamodel.Attribute)4 EmbeddableType (javax.persistence.metamodel.EmbeddableType)4 SingularAttribute (javax.persistence.metamodel.SingularAttribute)4 PathReference (com.blazebit.persistence.parser.expression.PathReference)3 LinkedHashMap (java.util.LinkedHashMap)3 MapKeyExpression (com.blazebit.persistence.parser.expression.MapKeyExpression)2 PathElementExpression (com.blazebit.persistence.parser.expression.PathElementExpression)2 PropertyExpression (com.blazebit.persistence.parser.expression.PropertyExpression)2 JpaProvider (com.blazebit.persistence.spi.JpaProvider)2 InverseRemoveStrategy (com.blazebit.persistence.view.InverseRemoveStrategy)2 AttributeAccessor (com.blazebit.persistence.view.impl.accessor.AttributeAccessor)2