Search in sources :

Example 1 with Type

use of com.blazebit.persistence.view.metamodel.Type in project blaze-persistence by Blazebit.

the class ViewMapper method createAccessor.

private ObjectMapper createAccessor(ManagedViewType<S> sourceType, ManagedViewType<T> targetType, boolean ignoreMissing, EntityViewKindMapping entityViewKindMapping, EntityViewManager entityViewManager, ProxyFactory proxyFactory, MethodAttribute<? super T, ?> targetAttribute, String prefix, Map<String, Key<Object, Object>> subMappers) {
    String newPrefix;
    if (prefix.isEmpty()) {
        newPrefix = targetAttribute.getName();
    } else {
        newPrefix = prefix + "." + targetAttribute.getName();
    }
    Type<?> attributeType;
    MappingConstructorImpl<?> constructor = null;
    Boolean maybeMarkNew = entityViewKindMapping == EntityViewKindMapping.MARK_NEW ? null : false;
    Key<Object, Object> subMapperKey = subMappers.get(newPrefix);
    if (subMapperKey == Key.EXCLUDE_MARKER) {
        return null;
    } else if (subMapperKey != null) {
        ignoreMissing = subMapperKey.ignoreMissing;
        maybeMarkNew = subMapperKey.markNew;
    }
    // Try to find a source attribute
    MethodAttribute<?, ?> sourceAttribute;
    AttributeAccessor accessor;
    if (sourceType == null) {
        sourceAttribute = null;
        if (targetAttribute.getMappingType() == Attribute.MappingType.PARAMETER) {
            return new ParameterObjectMapper(((MappingAttribute<?, ?>) targetAttribute).getMapping());
        }
        accessor = Accessors.forEntityMapping((EntityViewManagerImpl) entityViewManager, targetAttribute);
        if (accessor == null) {
            if (ignoreMissing) {
                return null;
            }
            throw inconvertible("Attribute '" + targetAttribute.getName() + "' from target type is missing in source type!", targetType);
        }
    } else {
        sourceAttribute = sourceType.getAttribute(targetAttribute.getName());
        if (sourceAttribute == null) {
            if (targetAttribute.getMappingType() == Attribute.MappingType.PARAMETER) {
                return new ParameterObjectMapper(((MappingAttribute<?, ?>) targetAttribute).getMapping());
            }
            // Optionally ignore missing attributes
            if (ignoreMissing) {
                return null;
            }
            throw inconvertible("Attribute '" + targetAttribute.getName() + "' from target type is missing in source type!", sourceType, targetType);
        }
        accessor = Accessors.forViewAttribute(null, sourceAttribute, true);
    }
    // Handle conversion from one type to another
    if (targetAttribute.isCollection()) {
        if ((sourceAttribute != null) && (targetAttribute.getConvertedJavaType() != sourceAttribute.getConvertedJavaType())) {
            throw inconvertible("Attribute '" + targetAttribute.getName() + "' from target type has a different plural type than in source type!", sourceType, targetType);
        }
        PluralAttribute<?, ?, ?> targetPluralAttr = (PluralAttribute<?, ?, ?>) targetAttribute;
        Type<?> elementType = (sourceAttribute == null) ? null : ((PluralAttribute<?, ?, ?>) sourceAttribute).getElementType();
        ViewMapper<Object, Object> valueMapper = null;
        attributeType = targetPluralAttr.getElementType();
        if (subMapperKey != null) {
            attributeType = subMapperKey.targetType;
            constructor = subMapperKey.targetConstructor;
        }
        if (targetAttribute.isSubview()) {
            valueMapper = createViewMapper(elementType, attributeType, constructor, ignoreMissing, maybeMarkNew, entityViewManager, proxyFactory, newPrefix, subMappers);
        } else if ((sourceType != null) && (targetPluralAttr.getElementType() != elementType)) {
            throw inconvertible("Attribute '" + targetAttribute.getName() + "' from target type has a different element type than in source type!", sourceType, targetType);
        }
        boolean needsDirtyTracker = ((AbstractAttribute<?, ?>) targetAttribute).needsDirtyTracker();
        if (targetPluralAttr.getCollectionType() == PluralAttribute.CollectionType.MAP) {
            MapAttribute<?, ?, ?> targetMapAttr = (MapAttribute<?, ?, ?>) targetAttribute;
            Type<?> keyType = (sourceAttribute == null) ? null : ((MapAttribute<?, ?, ?>) sourceAttribute).getKeyType();
            ViewMapper<Object, Object> keyMapper = null;
            if (targetMapAttr.isKeySubview()) {
                String newKeyPrefix = "KEY(" + newPrefix + ")";
                Key<Object, Object> keySubMapperKey = subMappers.get(newKeyPrefix);
                if (keySubMapperKey == Key.EXCLUDE_MARKER) {
                    keyMapper = null;
                } else {
                    constructor = null;
                    Type<?> keyTargetType = targetMapAttr.getKeyType();
                    Boolean maybeMarkNewKey = entityViewKindMapping == EntityViewKindMapping.MARK_NEW ? null : false;
                    if (subMapperKey != null) {
                        constructor = keySubMapperKey.targetConstructor;
                        keyTargetType = keySubMapperKey.targetType;
                        ignoreMissing = keySubMapperKey.ignoreMissing;
                        maybeMarkNewKey = keySubMapperKey.markNew;
                    }
                    keyMapper = createViewMapper(keyType, keyTargetType, constructor, ignoreMissing, maybeMarkNewKey, entityViewManager, proxyFactory, newPrefix, subMappers);
                }
            } else if ((sourceType != null) && (targetMapAttr.getKeyType() != keyType)) {
                throw inconvertible("Attribute '" + targetAttribute.getName() + "' from target type has a different key type than in source type!", sourceType, targetType);
            }
            MapInstantiatorImplementor<?, ?> mapInstantiator = ((AbstractAttribute<?, ?>) targetAttribute).getMapInstantiator();
            return new MapObjectMapper(accessor, needsDirtyTracker, entityViewKindMapping != EntityViewKindMapping.MARK_NEW, mapInstantiator, keyMapper, valueMapper);
        } else {
            CollectionInstantiatorImplementor<?, ?> collectionInstantiator = ((AbstractAttribute<?, ?>) targetAttribute).getCollectionInstantiator();
            return new CollectionObjectMapper(accessor, needsDirtyTracker, entityViewKindMapping != EntityViewKindMapping.MARK_NEW, collectionInstantiator, valueMapper);
        }
    } else if (targetAttribute.isSubview()) {
        attributeType = ((SingularAttribute<?, ?>) targetAttribute).getType();
        if (subMapperKey != null) {
            attributeType = subMapperKey.targetType;
            constructor = subMapperKey.targetConstructor;
        }
        Type<?> type = (sourceAttribute == null) ? null : ((SingularAttribute<?, ?>) sourceAttribute).getType();
        ViewMapper<Object, Object> mapper = createViewMapper(type, attributeType, constructor, ignoreMissing, maybeMarkNew, entityViewManager, proxyFactory, newPrefix, subMappers);
        return new AttributeObjectMapper(accessor, mapper);
    } else if ((sourceAttribute != null) && (targetAttribute.getConvertedJavaType() != sourceAttribute.getConvertedJavaType())) {
        throw inconvertible("Attribute '" + targetAttribute.getName() + "' from target type has a different type than in source type!", sourceType, targetType);
    } else {
        return new PassthroughObjectMapper(accessor);
    }
}
Also used : AbstractAttribute(com.blazebit.persistence.view.impl.metamodel.AbstractAttribute) EntityViewManagerImpl(com.blazebit.persistence.view.impl.EntityViewManagerImpl) PluralAttribute(com.blazebit.persistence.view.metamodel.PluralAttribute) MapAttribute(com.blazebit.persistence.view.metamodel.MapAttribute) SingularAttribute(com.blazebit.persistence.view.metamodel.SingularAttribute) Type(com.blazebit.persistence.view.metamodel.Type) ManagedViewType(com.blazebit.persistence.view.metamodel.ManagedViewType) ViewType(com.blazebit.persistence.view.metamodel.ViewType) AttributeAccessor(com.blazebit.persistence.view.impl.accessor.AttributeAccessor)

Example 2 with Type

use of com.blazebit.persistence.view.metamodel.Type in project blaze-persistence by Blazebit.

the class AbstractAttribute method checkAttribute.

public void checkAttribute(ManagedType<?> managedType, MetamodelBuildingContext context) {
    Class<?> expressionType = getJavaType();
    Class<?> keyType = null;
    Class<?> elementType = null;
    ManagedType<?> elementManagedType;
    javax.persistence.metamodel.Attribute<?, ?> elementAttribute;
    if (possibleTargetTypes.size() != 1) {
        if (getElementType() instanceof ManagedViewType<?>) {
            elementManagedType = context.getEntityMetamodel().getManagedType(((ManagedViewType<?>) getElementType()).getEntityClass());
        } else {
            elementManagedType = context.getEntityMetamodel().getManagedType(getElementType().getJavaType());
        }
        elementAttribute = null;
    } else {
        elementManagedType = context.getEntityMetamodel().getManagedType(possibleTargetTypes.get(0).getLeafBaseValueClass());
        elementAttribute = possibleTargetTypes.get(0).getLeafMethod();
    }
    ScalarTargetResolvingExpressionVisitor visitor = new ScalarTargetResolvingExpressionVisitor(elementManagedType, elementAttribute, context.getEntityMetamodel(), context.getJpqlFunctions(), declaringType.getEntityViewRootTypes());
    if (fetches.length != 0) {
        if (context.getEntityMetamodel().getManagedType(getElementType().getJavaType()) == null) {
            context.addError("Specifying fetches for non-entity attribute type [" + Arrays.toString(fetches) + "] at the " + getLocation() + " is not allowed!");
        } else {
            for (int i = 0; i < fetches.length; i++) {
                final String fetch = fetches[i];
                final String errorLocation;
                if (fetches.length == 1) {
                    errorLocation = "the fetch expression";
                } else {
                    errorLocation = "the " + (i + 1) + ". fetch expression";
                }
                visitor.clear();
                try {
                    // Validate the fetch expression parses
                    context.getExpressionFactory().createPathExpression(fetch).accept(visitor);
                } catch (SyntaxErrorException ex) {
                    try {
                        context.getExpressionFactory().createSimpleExpression(fetch, false, false, true);
                        // The used expression is not usable for fetches
                        context.addError("Invalid fetch expression '" + fetch + "' of the " + getLocation() + ". Simplify the fetch expression to a simple path expression. Encountered error: " + ex.getMessage());
                    } catch (SyntaxErrorException ex2) {
                        // This is a real syntax error
                        context.addError("Syntax error in " + errorLocation + " '" + fetch + "' of the " + getLocation() + ": " + ex.getMessage());
                    }
                } catch (IllegalArgumentException ex) {
                    context.addError("An error occurred while trying to resolve the " + errorLocation + " '" + fetch + "' of the " + getLocation() + ": " + ex.getMessage());
                }
            }
        }
    }
    if (limitExpression != null) {
        try {
            Expression inItemExpression = context.getTypeValidationExpressionFactory().createInItemExpression(limitExpression);
            if (!(inItemExpression instanceof ParameterExpression) && !(inItemExpression instanceof NumericLiteral) || inItemExpression instanceof NumericLiteral && ((NumericLiteral) inItemExpression).getNumericType() != NumericType.INTEGER) {
                context.addError("Syntax error in the limit expression '" + limitExpression + "' of the " + getLocation() + ": The expression must be a integer literal or a parameter expression");
            }
        } catch (SyntaxErrorException ex) {
            context.addError("Syntax error in the limit expression '" + limitExpression + "' of the " + getLocation() + ": " + ex.getMessage());
        } catch (IllegalArgumentException ex) {
            context.addError("An error occurred while trying to resolve the limit expression '" + limitExpression + "' of the " + getLocation() + ": " + ex.getMessage());
        }
        try {
            Expression inItemExpression = context.getTypeValidationExpressionFactory().createInItemExpression(offsetExpression);
            if (!(inItemExpression instanceof ParameterExpression) && !(inItemExpression instanceof NumericLiteral) || inItemExpression instanceof NumericLiteral && ((NumericLiteral) inItemExpression).getNumericType() != NumericType.INTEGER) {
                context.addError("Syntax error in the offset expression '" + offsetExpression + "' of the " + getLocation() + ": The expression must be a integer literal or a parameter expression");
            }
        } catch (SyntaxErrorException ex) {
            context.addError("Syntax error in the offset expression '" + offsetExpression + "' of the " + getLocation() + ": " + ex.getMessage());
        } catch (IllegalArgumentException ex) {
            context.addError("An error occurred while trying to resolve the offset expression '" + offsetExpression + "' of the " + getLocation() + ": " + ex.getMessage());
        }
        for (int i = 0; i < orderByItems.size(); i++) {
            OrderByItem orderByItem = orderByItems.get(i);
            String expression = orderByItem.getExpression();
            try {
                visitor.clear();
                context.getTypeValidationExpressionFactory().createSimpleExpression(expression, false, false, true).accept(visitor);
            } catch (SyntaxErrorException ex) {
                context.addError("Syntax error in the " + (i + 1) + "th order by expression '" + expression + "' of the " + getLocation() + ": " + ex.getMessage());
            } catch (IllegalArgumentException ex) {
                context.addError("An error occurred while trying to resolve the " + (i + 1) + "th order by expression '" + expression + "' of the " + getLocation() + ": " + ex.getMessage());
            }
        }
    }
    if (fetchStrategy == FetchStrategy.MULTISET) {
        if (getElementType() instanceof ManagedViewTypeImplementor<?> && ((ManagedViewTypeImplementor<?>) getElementType()).hasJpaManagedAttributes()) {
            context.addError("Using the MULTISET fetch strategy is not allowed when the subview contains attributes with entity types. MULTISET at the " + getLocation() + " is not allowed!");
        } else if (getElementType() instanceof BasicTypeImpl<?> && ((BasicTypeImpl<?>) getElementType()).isJpaManaged()) {
            context.addError("Using the MULTISET fetch strategy is not allowed with entity types. MULTISET at the " + getLocation() + " is not allowed!");
        }
    }
    Expression indexExpression = null;
    if (isCollection()) {
        elementType = getElementType().getJavaType();
        if (!isUpdatable()) {
            // Updatable collection attributes are specially handled in the type compatibility check
            if (isIndexed()) {
                if (getCollectionType() == PluralAttribute.CollectionType.MAP) {
                    expressionType = Collection.class;
                    keyType = getKeyType().getJavaType();
                } else {
                    expressionType = Collection.class;
                    keyType = Integer.class;
                }
            } else {
                // We can assign e.g. a Set to a List, so let's use the common supertype
                expressionType = Collection.class;
            }
        }
        if (isIndexed()) {
            if (getCollectionType() == PluralAttribute.CollectionType.MAP) {
                indexExpression = getKeyMappingExpression();
                String[] keyFetches = getKeyFetches();
                if (keyFetches.length != 0) {
                    ManagedType<?> managedKeyType = context.getEntityMetamodel().getManagedType(getKeyType().getJavaType());
                    if (managedKeyType == null) {
                        context.addError("Specifying key fetches for non-entity attribute key type [" + Arrays.toString(keyFetches) + "] at the " + getLocation() + " is not allowed!");
                    } else {
                        ScalarTargetResolvingExpressionVisitor keyVisitor = new ScalarTargetResolvingExpressionVisitor(managedKeyType, context.getEntityMetamodel(), context.getJpqlFunctions(), declaringType.getEntityViewRootTypes());
                        for (int i = 0; i < keyFetches.length; i++) {
                            final String fetch = keyFetches[i];
                            final String errorLocation;
                            if (keyFetches.length == 1) {
                                errorLocation = "the key fetch expression";
                            } else {
                                errorLocation = "the " + (i + 1) + ". key fetch expression";
                            }
                            keyVisitor.clear();
                            try {
                                // Validate the fetch expression parses
                                context.getExpressionFactory().createPathExpression(fetch).accept(keyVisitor);
                            } catch (SyntaxErrorException ex) {
                                try {
                                    context.getExpressionFactory().createSimpleExpression(fetch, false, false, true);
                                    // The used expression is not usable for fetches
                                    context.addError("Invalid key fetch expression '" + fetch + "' of the " + getLocation() + ". Simplify the key fetch expression to a simple path expression. Encountered error: " + ex.getMessage());
                                } catch (SyntaxErrorException ex2) {
                                    // This is a real syntax error
                                    context.addError("Syntax error in " + errorLocation + " '" + fetch + "' of the " + getLocation() + ": " + ex.getMessage());
                                }
                            } catch (IllegalArgumentException ex) {
                                context.addError("An error occurred while trying to resolve the " + errorLocation + " '" + fetch + "' of the " + getLocation() + ": " + ex.getMessage());
                            }
                        }
                    }
                }
            } else {
                indexExpression = getMappingIndexExpression();
            }
        }
    }
    if (isSubview()) {
        ManagedViewTypeImplementor<?> subviewType = (ManagedViewTypeImplementor<?>) getElementType();
        if (isCollection()) {
            elementType = subviewType.getEntityClass();
        } else {
            expressionType = subviewType.getEntityClass();
        }
    } else {
        // If we determined, that the java type is a basic type, let's double check if the user didn't do something wrong
        Class<?> elementJavaType = getElementType().getJavaType();
        if ((elementJavaType.getModifiers() & Modifier.ABSTRACT) != 0) {
            // If the element type has an entity view annotation, although it is considered basic, we throw an error as this means, the view was probably not registered
            if (!isQueryParameter() && AnnotationUtils.findAnnotation(elementJavaType, EntityView.class) != null && getElementType().getConvertedType() == null) {
                context.addError("The element type '" + elementJavaType.getName() + "' is considered basic although the class is annotated with @EntityView. Add a type converter or add the java class to the entity view configuration! Problematic attribute " + getLocation());
            }
        }
    }
    if (isKeySubview()) {
        keyType = ((ManagedViewTypeImplementor<?>) getKeyType()).getEntityClass();
    }
    if (keyType != null) {
        validateTypesCompatible(possibleIndexTargetTypes, keyType, null, isUpdatable(), true, context, ExpressionLocation.MAPPING_INDEX, getLocation());
    }
    if (isCorrelated()) {
        // Validate that resolving "correlationBasis" on "managedType" is valid
        validateTypesCompatible(managedType, correlationBasisExpression, Object.class, null, false, true, declaringType.getEntityViewRootTypes(), context, ExpressionLocation.CORRELATION_BASIS, getLocation());
        if (correlated != null) {
            // Validate that resolving "correlationResult" on "correlated" is compatible with "expressionType" and "elementType"
            validateTypesCompatible(possibleTargetTypes, expressionType, elementType, false, !isCollection(), context, ExpressionLocation.CORRELATION_RESULT, getLocation());
            Predicate correlationPredicate = getCorrelationPredicate();
            if (correlationPredicate != null) {
                ExpressionFactory ef = context.getTypeValidationExpressionFactory();
                // First we need to prefix the correlation basis expression with an alias because we use that in the predicate
                PrefixingQueryGenerator prefixingQueryGenerator = new PrefixingQueryGenerator(ef, correlationKeyAlias, null, null, declaringType.getEntityViewRootTypes().keySet(), false, false);
                prefixingQueryGenerator.setQueryBuffer(new StringBuilder());
                correlationBasisExpression.accept(prefixingQueryGenerator);
                // Next we replace the plain alias usage with the prefixed correlation basis expression
                AliasReplacementVisitor aliasReplacementVisitor = new AliasReplacementVisitor(ef.createSimpleExpression(prefixingQueryGenerator.getQueryBuffer().toString()), correlationKeyAlias);
                correlationPredicate = correlationPredicate.copy(ExpressionCopyContext.EMPTY);
                correlationPredicate.accept(aliasReplacementVisitor);
                // Finally we validate that the expression
                try {
                    Map<String, javax.persistence.metamodel.Type<?>> rootTypes = new HashMap<>(declaringType.getEntityViewRootTypes());
                    rootTypes.put(correlationKeyAlias, managedType);
                    ScalarTargetResolvingExpressionVisitor correlationVisitor = new ScalarTargetResolvingExpressionVisitor(correlated, context.getEntityMetamodel(), context.getJpqlFunctions(), rootTypes);
                    correlationPredicate.accept(correlationVisitor);
                } catch (SyntaxErrorException ex) {
                    context.addError("Syntax error in the condition expression '" + correlationPredicate + "' of the " + getLocation() + ": " + ex.getMessage());
                } catch (IllegalArgumentException ex) {
                    context.addError("An error occurred while trying to resolve the condition expression '" + correlationPredicate + "' of the " + getLocation() + ": " + ex.getMessage());
                }
            }
        }
    } else if (isSubquery()) {
        if (subqueryExpression != null && !subqueryExpression.isEmpty()) {
            // If a converter is applied, we already know that there was a type match with the underlying type
            if (getElementType().getConvertedType() == null) {
                validateTypesCompatible(possibleTargetTypes, expressionType, elementType, false, !isCollection(), context, ExpressionLocation.SUBQUERY_EXPRESSION, getLocation());
            }
        }
    } else if (!isQueryParameter()) {
        // Forcing singular via @MappingSingular
        if (!isCollection() && (Collection.class.isAssignableFrom(expressionType) || Map.class.isAssignableFrom(expressionType))) {
            Class<?>[] typeArguments = getTypeArguments();
            elementType = typeArguments[typeArguments.length - 1];
        }
        // If a converter is applied, we already know that there was a type match with the underlying type
        if (getElementType().getConvertedType() == null) {
            // Validate that resolving "mapping" on "managedType" is compatible with "expressionType" and "elementType"
            validateTypesCompatible(possibleTargetTypes, expressionType, elementType, isUpdatable(), !isCollection(), context, ExpressionLocation.MAPPING, getLocation());
        }
        if (isMutable() && (declaringType.isUpdatable() || declaringType.isCreatable())) {
            UpdatableExpressionVisitor updatableVisitor = new UpdatableExpressionVisitor(context.getEntityMetamodel(), managedType.getJavaType(), isUpdatable(), declaringType.getEntityViewRootTypes());
            try {
                // NOTE: Not supporting "this" here because it doesn't make sense to have an updatable mapping that refers to this
                // The only thing that might be interesting is supporting "this" when we support cascading as properties could be nested
                // But not sure yet if the embeddable attributes would then be modeled as "updatable".
                // I guess these attributes are not "updatable" but that probably depends on the decision regarding collections as they have a similar problem
                // A collection itself might not be "updatable" but it's elements could be. This is roughly the same problem
                mappingExpression.accept(updatableVisitor);
                Map<javax.persistence.metamodel.Attribute<?, ?>, javax.persistence.metamodel.Type<?>> possibleTargets = updatableVisitor.getPossibleTargets();
                if (possibleTargets.size() > 1) {
                    context.addError("Multiple possible target type for the mapping in the " + getLocation() + ": " + possibleTargets);
                }
                // TODO: maybe allow to override this per-attribute?
                if (isDisallowOwnedUpdatableSubview()) {
                    for (Type<?> updateCascadeAllowedSubtype : getUpdateCascadeAllowedSubtypes()) {
                        ManagedViewType<?> managedViewType = (ManagedViewType<?>) updateCascadeAllowedSubtype;
                        if (managedViewType.isUpdatable()) {
                            context.addError("Invalid use of @UpdatableEntityView type '" + managedViewType.getJavaType().getName() + "' for the " + getLocation() + ". Consider using a read-only view type instead or use @AllowUpdatableEntityViews! " + "For further information on this topic, please consult the documentation https://persistence.blazebit.com/documentation/entity-view/manual/en_US/index.html#updatable-mappings-subview");
                        }
                    }
                }
            } catch (IllegalArgumentException ex) {
                context.addError("There is an error for the " + getLocation() + ": " + ex.getMessage());
            }
            if (isUpdatable()) {
                if (isCollection() && getElementCollectionType() != null) {
                    context.addError("The use of a multi-collection i.e. List<Collection<?>> or Map<?, Collection<?>> at the " + getLocation() + " is unsupported for updatable collections!");
                }
            }
            if ((isUpdatable() || isKeySubview() && ((ManagedViewTypeImplementor<?>) getKeyType()).isUpdatable()) && indexExpression != null) {
                boolean invalid;
                if (getCollectionType() == PluralAttribute.CollectionType.MAP) {
                    invalid = !(indexExpression instanceof MapKeyExpression) || !"this".equals(((MapKeyExpression) indexExpression).getPath().getPath());
                } else {
                    invalid = !(indexExpression instanceof ListIndexExpression) || !"this".equals(((ListIndexExpression) indexExpression).getPath().getPath());
                }
                if (invalid) {
                    context.addError("The @MappingIndex at the " + getLocation() + " is a complex mapping and can thus not be updatable!");
                }
            }
        }
    }
}
Also used : NumericLiteral(com.blazebit.persistence.parser.expression.NumericLiteral) HashMap(java.util.HashMap) MapAttribute(javax.persistence.metamodel.MapAttribute) PluralAttribute(com.blazebit.persistence.view.metamodel.PluralAttribute) ExtendedAttribute(com.blazebit.persistence.spi.ExtendedAttribute) ListAttribute(javax.persistence.metamodel.ListAttribute) Attribute(com.blazebit.persistence.view.metamodel.Attribute) Predicate(com.blazebit.persistence.parser.predicate.Predicate) AliasReplacementVisitor(com.blazebit.persistence.parser.AliasReplacementVisitor) MapKeyExpression(com.blazebit.persistence.parser.expression.MapKeyExpression) OrderByItem(com.blazebit.persistence.view.metamodel.OrderByItem) ListIndexExpression(com.blazebit.persistence.parser.expression.ListIndexExpression) UpdatableExpressionVisitor(com.blazebit.persistence.view.impl.UpdatableExpressionVisitor) ManagedViewType(com.blazebit.persistence.view.metamodel.ManagedViewType) ExpressionFactory(com.blazebit.persistence.parser.expression.ExpressionFactory) EntityView(com.blazebit.persistence.view.EntityView) SyntaxErrorException(com.blazebit.persistence.parser.expression.SyntaxErrorException) ScalarTargetResolvingExpressionVisitor(com.blazebit.persistence.view.impl.ScalarTargetResolvingExpressionVisitor) TargetType(com.blazebit.persistence.view.impl.ScalarTargetResolvingExpressionVisitor.TargetType) NumericType(com.blazebit.persistence.parser.expression.NumericType) ManagedType(javax.persistence.metamodel.ManagedType) Type(com.blazebit.persistence.view.metamodel.Type) ExtendedManagedType(com.blazebit.persistence.spi.ExtendedManagedType) ManagedViewType(com.blazebit.persistence.view.metamodel.ManagedViewType) ViewType(com.blazebit.persistence.view.metamodel.ViewType) ListIndexExpression(com.blazebit.persistence.parser.expression.ListIndexExpression) Expression(com.blazebit.persistence.parser.expression.Expression) ParameterExpression(com.blazebit.persistence.parser.expression.ParameterExpression) PathExpression(com.blazebit.persistence.parser.expression.PathExpression) PropertyExpression(com.blazebit.persistence.parser.expression.PropertyExpression) NullExpression(com.blazebit.persistence.parser.expression.NullExpression) MapKeyExpression(com.blazebit.persistence.parser.expression.MapKeyExpression) ParameterExpression(com.blazebit.persistence.parser.expression.ParameterExpression) Collection(java.util.Collection) PrefixingQueryGenerator(com.blazebit.persistence.view.impl.PrefixingQueryGenerator) Map(java.util.Map) HashMap(java.util.HashMap)

Example 3 with Type

use of com.blazebit.persistence.view.metamodel.Type in project blaze-persistence by Blazebit.

the class EntityViewUpdaterImpl method createPluralAttributeSubFlusher.

private DirtyAttributeFlusher<?, ?, ?> createPluralAttributeSubFlusher(EntityViewManagerImpl evm, Map<Object, EntityViewUpdaterImpl> localCache, ManagedViewTypeImplementor<?> viewType, AbstractMethodAttribute<?, ?> attribute, String name, Type<?> type, EntityViewUpdaterImpl owner, String ownerMapping) {
    EntityMetamodel entityMetamodel = evm.getMetamodel().getEntityMetamodel();
    String attributeName = attribute.getName() + "_" + name;
    String attributeMapping = attribute.getMapping();
    String attributeLocation = attribute.getLocation();
    Set<Type<?>> readOnlyAllowedSubtypes = attribute.getReadOnlyAllowedSubtypes();
    Set<Type<?>> persistAllowedSubtypes = attribute.getPersistCascadeAllowedSubtypes();
    Set<Type<?>> updateAllowedSubtypes = attribute.getUpdateCascadeAllowedSubtypes();
    if (type instanceof ManagedViewType<?>) {
        ManagedViewTypeImplementor<?> subviewType = (ManagedViewTypeImplementor<?>) type;
        if (!(subviewType.getJpaManagedType() instanceof EntityType<?>)) {
            // 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), false, null, owner, ownerMapping == null ? attributeMapping : ownerMapping + "." + attributeMapping, localCache);
            String parameterName = attributeName + "_";
            String updateFragment = attributeMapping + ".";
            return new EmbeddableAttributeFlusher<>(attributeName, attributeMapping, updateFragment, parameterName, false, false, false, null, null, viewToEntityMapper);
        } else {
            ViewTypeImplementor<?> attributeViewType = (ViewTypeImplementor<?>) subviewType;
            InitialValueAttributeAccessor viewAttributeAccessor = Accessors.forMutableViewAttribute(evm, attribute);
            AttributeAccessor subviewIdAccessor;
            ManagedType<?> ownerManagedType = owner == null ? viewType.getJpaManagedType() : owner.managedViewType.getJpaManagedType();
            EntityType<?> ownerEntityType = ownerManagedType instanceof EntityType<?> ? (EntityType<?>) ownerManagedType : null;
            String attributeElementIdMapping;
            if (ownerEntityType != null && attribute.getMapping() != null) {
                ExtendedManagedType<?> extendedManagedType = evm.getMetamodel().getEntityMetamodel().getManagedType(ExtendedManagedType.class, attributeViewType.getEntityClass());
                attributeElementIdMapping = TypeDescriptor.getAttributeElementIdentifier(evm, 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);
                }
            } else {
                idComponentMappings = Collections.singletonList(attributeMapping + "." + attributeElementIdMapping);
            }
            String[] idAttributeMappings = idComponentMappings.toArray(new String[idComponentMappings.size()]);
            ViewToEntityMapper viewToEntityMapper = createViewToEntityMapper(attributeLocation, evm, localCache, ownerEntityType, attributeName, attributeMapping, attributeViewType, false, false, readOnlyAllowedSubtypes, persistAllowedSubtypes, updateAllowedSubtypes, EntityLoaders.referenceLoaderForAttribute(evm, localCache, attributeViewType, attribute.getViewTypes(), attributeElementIdMapping), owner, ownerMapping);
            String parameterName = attributeName;
            return new SubviewAttributeFlusher<>(attributeName, attributeMapping, false, true, false, false, false, subviewType.getConverter(), false, idAttributeMappings, parameterName, false, owner != null, null, viewAttributeAccessor, subviewIdAccessor, viewToEntityMapper, null, null);
        }
    } else {
        TypeDescriptor elementDescriptor = TypeDescriptor.forType(evm, localCache, this, attribute, type, owner, ownerMapping);
        String parameterName = attributeName;
        String updateFragment = attributeMapping;
        // TODO: Why?
        boolean supportsQueryFlush = !elementDescriptor.isJpaEmbeddable();
        return new BasicAttributeFlusher<>(attributeName, attributeMapping, supportsQueryFlush, false, true, false, false, false, null, elementDescriptor, updateFragment, parameterName, null, null, null, null, null);
    }
}
Also used : ViewTypeImplementor(com.blazebit.persistence.view.impl.metamodel.ViewTypeImplementor) ManagedViewTypeImplementor(com.blazebit.persistence.view.impl.metamodel.ManagedViewTypeImplementor) Set(java.util.Set) HashSet(java.util.HashSet) 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) 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) SubviewAttributeFlusher(com.blazebit.persistence.view.impl.update.flush.SubviewAttributeFlusher) ManagedViewType(com.blazebit.persistence.view.metamodel.ManagedViewType) ManagedViewTypeImplementor(com.blazebit.persistence.view.impl.metamodel.ManagedViewTypeImplementor) EntityType(javax.persistence.metamodel.EntityType) 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) TypeDescriptor(com.blazebit.persistence.view.impl.update.flush.TypeDescriptor) BasicAttributeFlusher(com.blazebit.persistence.view.impl.update.flush.BasicAttributeFlusher) InitialValueAttributeAccessor(com.blazebit.persistence.view.impl.accessor.InitialValueAttributeAccessor) AttributeAccessor(com.blazebit.persistence.view.impl.accessor.AttributeAccessor) EntityMetamodel(com.blazebit.persistence.parser.EntityMetamodel) EmbeddableUpdaterBasedViewToEntityMapper(com.blazebit.persistence.view.impl.entity.EmbeddableUpdaterBasedViewToEntityMapper)

Example 4 with Type

use of com.blazebit.persistence.view.metamodel.Type in project blaze-persistence by Blazebit.

the class TypeDescriptor method forType.

public static TypeDescriptor forType(EntityViewManagerImpl evm, Map<Object, EntityViewUpdaterImpl> localCache, EntityViewUpdaterImpl updater, AbstractMethodAttribute<?, ?> attribute, Type<?> type, EntityViewUpdaterImpl owner, String ownerMapping) {
    EntityMetamodel entityMetamodel = evm.getMetamodel().getEntityMetamodel();
    String attributeLocation = attribute.getLocation();
    boolean cascadePersist = attribute.isPersistCascaded();
    boolean cascadeUpdate = attribute.isUpdateCascaded();
    Set<Type<?>> readOnlyAllowedSubtypes = attribute.getReadOnlyAllowedSubtypes();
    Set<Type<?>> persistAllowedSubtypes = attribute.getPersistCascadeAllowedSubtypes();
    Set<Type<?>> updateAllowedSubtypes = attribute.getUpdateCascadeAllowedSubtypes();
    EntityToEntityMapper entityToEntityMapper = null;
    ViewToEntityMapper viewToEntityMapper = null;
    ViewToEntityMapper loadOnlyViewToEntityMapper = null;
    final ManagedType<?> managedType = entityMetamodel.getManagedType(type.getJavaType());
    final boolean jpaEntity = managedType instanceof EntityType<?>;
    final boolean jpaManaged = managedType != null;
    final boolean mutable;
    final boolean identifiable;
    TypeConverter<Object, Object> converter = (TypeConverter<Object, Object>) type.getConverter();
    BasicUserType<Object> basicUserType;
    ManagedType<?> ownerEntityType = owner == null ? attribute.getDeclaringType().getJpaManagedType() : owner.getManagedViewType().getJpaManagedType();
    String attributeIdAttributeName = null;
    String entityIdAttributeName = null;
    Class<?> jpaType;
    // TODO: currently we only check if the declared type is mutable, but we have to let the collection flusher which types are considered updatable/creatable
    if (type instanceof BasicType<?>) {
        jpaType = type.getJavaType();
        basicUserType = (BasicUserType<Object>) ((BasicType<?>) type).getUserType();
        mutable = basicUserType.isMutable();
        identifiable = jpaEntity || !jpaManaged;
        if (jpaEntity) {
            Map<String, Map<?, ?>> fetchGraph = null;
            UnmappedAttributeCascadeDeleter deleter = null;
            // We only need to know the fetch graph when we actually do updates
            if (cascadeUpdate) {
                fetchGraph = getFetchGraph(attribute.getFetches(), attribute.getMapping(), managedType);
            }
            if (ownerEntityType instanceof EntityType<?>) {
                ExtendedManagedType<?> extendedManagedType = evm.getMetamodel().getEntityMetamodel().getManagedType(ExtendedManagedType.class, type.getJavaType());
                entityIdAttributeName = extendedManagedType.getIdAttribute().getName();
                attributeIdAttributeName = getAttributeElementIdentifier(evm, (EntityType<?>) ownerEntityType, attribute.getName(), ownerMapping, attribute.getMapping(), extendedManagedType.getType());
                // Only construct when orphanRemoval or delete cascading is enabled, orphanRemoval implies delete cascading
                if (attribute.isDeleteCascaded()) {
                    String mapping = attribute.getMapping();
                    ExtendedManagedType elementManagedType = entityMetamodel.getManagedType(ExtendedManagedType.class, attribute.getDeclaringType().getJpaManagedType());
                    deleter = new UnmappedBasicAttributeCascadeDeleter(evm, mapping, elementManagedType.getAttribute(mapping), mapping + "." + attributeIdAttributeName, false);
                }
            }
            // TODO: EntityToEntityMapper should also use the attributeIdAttributeName
            entityToEntityMapper = new DefaultEntityToEntityMapper(cascadePersist, cascadeUpdate, jpaType, basicUserType, new DefaultEntityLoaderFetchGraphNode(evm, attribute.getName(), (EntityType<?>) managedType, fetchGraph), deleter);
        }
    } else {
        ManagedViewTypeImplementor<?> elementType = (ManagedViewTypeImplementor<?>) type;
        jpaType = elementType.getEntityClass();
        basicUserType = null;
        mutable = elementType.isUpdatable() || elementType.isCreatable() || !persistAllowedSubtypes.isEmpty() || !updateAllowedSubtypes.isEmpty();
        Set<ManagedViewType<?>> viewTypes = attribute.getViewTypes();
        if (elementType.getJpaManagedType() instanceof EntityType<?> && ownerEntityType instanceof EntityType<?>) {
            ExtendedManagedType<?> extendedManagedType = evm.getMetamodel().getEntityMetamodel().getManagedType(ExtendedManagedType.class, elementType.getEntityClass());
            entityIdAttributeName = extendedManagedType.getIdAttribute().getName();
            attributeIdAttributeName = getAttributeElementIdentifier(evm, (EntityType<?>) ownerEntityType, attribute.getName(), ownerMapping, attribute.getMapping(), extendedManagedType.getType());
        }
        viewToEntityMapper = createViewToEntityMapper(evm, localCache, updater, attributeIdAttributeName, attribute.getMapping(), attributeLocation, elementType, cascadePersist, cascadeUpdate, readOnlyAllowedSubtypes, persistAllowedSubtypes, updateAllowedSubtypes, EntityLoaders.referenceLoaderForAttribute(evm, localCache, elementType, viewTypes, attributeIdAttributeName), owner, ownerMapping);
        loadOnlyViewToEntityMapper = createLoadOnlyViewToEntityMapper(attributeLocation, evm, localCache, attributeIdAttributeName, attribute.getMapping(), elementType, cascadePersist, cascadeUpdate, readOnlyAllowedSubtypes, persistAllowedSubtypes, updateAllowedSubtypes, EntityLoaders.referenceLoaderForAttribute(evm, localCache, elementType, viewTypes, attributeIdAttributeName), owner, ownerMapping);
        identifiable = viewToEntityMapper.getViewIdAccessor() != null;
    }
    final boolean shouldJpaMerge = jpaEntity && mutable && cascadeUpdate;
    final boolean shouldJpaPersist = jpaEntity && mutable && cascadePersist;
    final boolean shouldFlushUpdates = cascadeUpdate && !updateAllowedSubtypes.isEmpty();
    final boolean shouldFlushPersists = cascadePersist && !persistAllowedSubtypes.isEmpty();
    return new TypeDescriptor(mutable, identifiable, jpaManaged, jpaEntity, shouldJpaMerge, shouldJpaPersist, shouldFlushPersists, shouldFlushUpdates, entityIdAttributeName, attributeIdAttributeName, jpaType, converter, basicUserType, entityToEntityMapper, viewToEntityMapper, loadOnlyViewToEntityMapper);
}
Also used : BasicType(com.blazebit.persistence.view.metamodel.BasicType) EntityToEntityMapper(com.blazebit.persistence.view.impl.entity.EntityToEntityMapper) DefaultEntityToEntityMapper(com.blazebit.persistence.view.impl.entity.DefaultEntityToEntityMapper) DefaultEntityLoaderFetchGraphNode(com.blazebit.persistence.view.impl.entity.DefaultEntityLoaderFetchGraphNode) LoadOrPersistViewToEntityMapper(com.blazebit.persistence.view.impl.entity.LoadOrPersistViewToEntityMapper) EmbeddableUpdaterBasedViewToEntityMapper(com.blazebit.persistence.view.impl.entity.EmbeddableUpdaterBasedViewToEntityMapper) UpdaterBasedViewToEntityMapper(com.blazebit.persistence.view.impl.entity.UpdaterBasedViewToEntityMapper) ViewToEntityMapper(com.blazebit.persistence.view.impl.entity.ViewToEntityMapper) ManagedViewType(com.blazebit.persistence.view.metamodel.ManagedViewType) DefaultEntityToEntityMapper(com.blazebit.persistence.view.impl.entity.DefaultEntityToEntityMapper) ManagedViewTypeImplementor(com.blazebit.persistence.view.impl.metamodel.ManagedViewTypeImplementor) ExtendedManagedType(com.blazebit.persistence.spi.ExtendedManagedType) EntityType(javax.persistence.metamodel.EntityType) TypeConverter(com.blazebit.persistence.view.spi.type.TypeConverter) BasicType(com.blazebit.persistence.view.metamodel.BasicType) EntityType(javax.persistence.metamodel.EntityType) Type(com.blazebit.persistence.view.metamodel.Type) BasicUserType(com.blazebit.persistence.view.spi.type.BasicUserType) ExtendedManagedType(com.blazebit.persistence.spi.ExtendedManagedType) MutableBasicUserType(com.blazebit.persistence.view.spi.type.MutableBasicUserType) ManagedType(javax.persistence.metamodel.ManagedType) ManagedViewType(com.blazebit.persistence.view.metamodel.ManagedViewType) ViewType(com.blazebit.persistence.view.metamodel.ViewType) EntityMetamodel(com.blazebit.persistence.parser.EntityMetamodel) HashMap(java.util.HashMap) Map(java.util.Map)

Example 5 with Type

use of com.blazebit.persistence.view.metamodel.Type 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)

Aggregations

ManagedViewType (com.blazebit.persistence.view.metamodel.ManagedViewType)7 Type (com.blazebit.persistence.view.metamodel.Type)7 ManagedType (javax.persistence.metamodel.ManagedType)6 BasicType (com.blazebit.persistence.view.metamodel.BasicType)5 ViewType (com.blazebit.persistence.view.metamodel.ViewType)5 ExtendedManagedType (com.blazebit.persistence.spi.ExtendedManagedType)4 PluralAttribute (com.blazebit.persistence.view.metamodel.PluralAttribute)4 HashMap (java.util.HashMap)4 EntityMetamodel (com.blazebit.persistence.parser.EntityMetamodel)3 ExtendedAttribute (com.blazebit.persistence.spi.ExtendedAttribute)3 AttributeAccessor (com.blazebit.persistence.view.impl.accessor.AttributeAccessor)3 EmbeddableUpdaterBasedViewToEntityMapper (com.blazebit.persistence.view.impl.entity.EmbeddableUpdaterBasedViewToEntityMapper)3 LoadOrPersistViewToEntityMapper (com.blazebit.persistence.view.impl.entity.LoadOrPersistViewToEntityMapper)3 UpdaterBasedViewToEntityMapper (com.blazebit.persistence.view.impl.entity.UpdaterBasedViewToEntityMapper)3 ViewToEntityMapper (com.blazebit.persistence.view.impl.entity.ViewToEntityMapper)3 ManagedViewTypeImplementor (com.blazebit.persistence.view.impl.metamodel.ManagedViewTypeImplementor)3 MapAttribute (com.blazebit.persistence.view.metamodel.MapAttribute)3 MethodAttribute (com.blazebit.persistence.view.metamodel.MethodAttribute)3 Attribute (javax.persistence.metamodel.Attribute)3 SingularAttribute (javax.persistence.metamodel.SingularAttribute)3