Search in sources :

Example 1 with BasicTypeImpl

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

the class ProxyFactory method addSetter.

private CtMethod addSetter(AbstractMethodAttribute<?, ?> attribute, CtClass cc, CtField attributeField, String methodName, CtField mutableStateField, boolean dirtyChecking, boolean isId) throws CannotCompileException, NotFoundException {
    FieldInfo finfo = attributeField.getFieldInfo2();
    String fieldType = finfo.getDescriptor();
    String desc = "(" + fieldType + ")V";
    ConstPool cp = finfo.getConstPool();
    MethodInfo minfo = new MethodInfo(cp, methodName, desc);
    minfo.setAccessFlags(AccessFlag.PUBLIC);
    String fieldName = finfo.getName();
    StringBuilder sb = new StringBuilder();
    sb.append("{\n");
    boolean invalidSetter = false;
    // When the declaring type is updatable/creatable we only allow setting the id value on new objects
    if (isId) {
        if (attribute != null && attribute.getDeclaringType().isCreatable()) {
            sb.append("\tif ($0.$$_kind != (byte) 2) {\n");
            sb.append("\t\tthrow new IllegalArgumentException(\"Updating the id attribute '").append(attribute.getName()).append("' is only allowed for new entity view objects created via EntityViewManager.create()!\");\n");
            sb.append("\t}\n");
        } else if (attribute != null && attribute.getDeclaringType().isUpdatable()) {
            sb.append("\tthrow new IllegalArgumentException(\"Updating the id attribute '").append(attribute.getName()).append("' is only allowed for new entity view objects created via EntityViewManager.create()!\");\n");
            invalidSetter = true;
        }
    }
    // Disallow calling the setter on a mutable only relation with objects of a different identity as that might indicate a programming error
    if (attribute != null && attribute.getDirtyStateIndex() != -1 && !attribute.isUpdatable() && (attribute.getDeclaringType().isCreatable() || attribute.getDeclaringType().isUpdatable())) {
        sb.append("\tObject tmp;\n");
        sb.append("\tif ($1 != $0.").append(fieldName);
        if (attribute.isCollection()) {
        // TODO: We could theoretically support collections too by looking into them and asserting equality element-wise
        } else {
            SingularAttribute<?, ?> singularAttribute = (SingularAttribute<?, ?>) attribute;
            Type<?> type = singularAttribute.getType();
            if (attribute.isSubview()) {
                if (!(type instanceof FlatViewType<?>)) {
                    String idMethodName = ((ViewType<?>) type).getIdAttribute().getJavaMethod().getName();
                    sb.append(" && ");
                    sb.append("($1 == null || (tmp = $1.");
                    sb.append(idMethodName);
                    sb.append("()) == null || !java.util.Objects.equals(tmp, $0.");
                    sb.append(fieldName);
                    sb.append('.').append(idMethodName);
                    sb.append("()))");
                }
            } else {
                BasicTypeImpl<?> basicType = (BasicTypeImpl<?>) type;
                boolean jpaEntity = basicType.isJpaEntity();
                if (jpaEntity) {
                    IdentifiableType<?> identifiableType = (IdentifiableType<?>) basicType.getManagedType();
                    for (javax.persistence.metamodel.SingularAttribute<?, ?> idAttribute : JpaMetamodelUtils.getIdAttributes(identifiableType)) {
                        Class<?> idClass = JpaMetamodelUtils.resolveFieldClass(basicType.getJavaType(), idAttribute);
                        String idAccessor = addIdAccessor(cc, identifiableType, idAttribute, pool.get(idClass.getName()));
                        sb.append(" && ");
                        sb.append("($1 == null || (tmp = ");
                        sb.append(idAccessor);
                        sb.append("($1)) == null || !java.util.Objects.equals(tmp, ");
                        sb.append(idAccessor);
                        sb.append("($0.");
                        sb.append(fieldName);
                        sb.append(")))");
                    }
                }
            }
        }
        sb.append(") {\n");
        sb.append("\t\tthrow new IllegalArgumentException(\"Updating the mutable-only attribute '").append(attribute.getName()).append("' with a value that has not the same identity is not allowed! Consider making the attribute updatable or update the value directly instead of replacing it!\");\n");
        sb.append("\t}\n");
    }
    if (attribute != null && attribute.isUpdatable() && dirtyChecking) {
        if (attribute.isCollection()) {
            if (strictCascadingCheck) {
                // With strict cascading checks enabled, we don't allow setting collections of mutable subviews
                boolean mutableElement = !attribute.getUpdateCascadeAllowedSubtypes().isEmpty() || !attribute.getPersistCascadeAllowedSubtypes().isEmpty();
                if (mutableElement && ((AbstractMethodPluralAttribute<?, ?, ?>) attribute).getElementType().getMappingType() != Type.MappingType.BASIC) {
                    sb.append("\t\tthrow new IllegalArgumentException(\"Replacing a collection that PERSIST or UPDATE cascades is prohibited by default! Instead, replace the contents by doing clear() and addAll()!\");\n");
                }
            }
        } else {
            // Only consider subviews here for now
            if (attribute.isSubview()) {
                String subtypeArray = addAllowedSubtypeField(cc, attribute);
                addParentRequiringUpdateSubtypesField(cc, attribute);
                addParentRequiringCreateSubtypesField(cc, attribute);
                sb.append("\tif ($1 != null) {\n");
                sb.append("\t\tClass c;\n");
                sb.append("\t\tboolean isNew;\n");
                sb.append("\t\tif ($1 instanceof ").append(EntityViewProxy.class.getName()).append(") {\n");
                sb.append("\t\t\tc = ((").append(EntityViewProxy.class.getName()).append(") $1).$$_getEntityViewClass();\n");
                sb.append("\t\t\tisNew = ((").append(EntityViewProxy.class.getName()).append(") $1).$$_isNew();\n");
                sb.append("\t\t} else {\n");
                sb.append("\t\t\tc = $1.getClass();\n");
                sb.append("\t\t\tisNew = false;\n");
                sb.append("\t\t}\n");
                sb.append("\t\tif (!").append(attributeField.getDeclaringClass().getName()).append('#').append(attribute.getName()).append("_$$_subtypes.contains(c)) {\n");
                sb.append("\t\t\tthrow new IllegalArgumentException(");
                sb.append("\"Allowed subtypes for attribute '").append(attribute.getName()).append("' are [").append(subtypeArray).append("] but got an instance of: \"");
                sb.append(".concat(c.getName())");
                sb.append(");\n");
                sb.append("\t\t}\n");
                if (strictCascadingCheck) {
                    sb.append("\t\tif ($0 != $1 && !isNew && ").append(attributeField.getDeclaringClass().getName()).append('#').append(attribute.getName()).append("_$$_parentRequiringUpdateSubtypes.contains(c) && !((").append(DirtyTracker.class.getName()).append(") $1).$$_hasParent()) {\n");
                    sb.append("\t\t\tthrow new IllegalArgumentException(");
                    sb.append("\"Setting instances of type [\" + c.getName() + \"] on attribute '").append(attribute.getName()).append("' is not allowed until they are assigned to an attribute that cascades the type! ");
                    sb.append("If you want this attribute to cascade, annotate it with @UpdatableMapping(cascade = { UPDATE }). You can also turn off strict cascading checks by setting ConfigurationProperties.UPDATER_STRICT_CASCADING_CHECK to false\"");
                    sb.append(");\n");
                    sb.append("\t\t}\n");
                    sb.append("\t\tif ($0 != $1 && isNew && ").append(attributeField.getDeclaringClass().getName()).append('#').append(attribute.getName()).append("_$$_parentRequiringCreateSubtypes.contains(c) && !((").append(DirtyTracker.class.getName()).append(") $1).$$_hasParent()) {\n");
                    sb.append("\t\t\tthrow new IllegalArgumentException(");
                    sb.append("\"Setting instances of type [\" + c.getName() + \"] on attribute '").append(attribute.getName()).append("' is not allowed until they are assigned to an attribute that cascades the type! ");
                    sb.append("If you want this attribute to cascade, annotate it with @UpdatableMapping(cascade = { PERSIST }). You can also turn off strict cascading checks by setting ConfigurationProperties.UPDATER_STRICT_CASCADING_CHECK to false\"");
                    sb.append(");\n");
                    sb.append("\t\t}\n");
                }
                sb.append("\t}\n");
            }
        }
    }
    if (attribute != null && attribute.getDirtyStateIndex() != -1) {
        int mutableStateIndex = attribute.getDirtyStateIndex();
        // Unset previous object parent
        if (attribute.isCollection()) {
            sb.append("\tif ($0.").append(fieldName).append(" != null && $0.").append(fieldName).append(" != $1) {\n");
            if (attribute instanceof MapAttribute<?, ?, ?>) {
                sb.append("\t\tif ($0.").append(fieldName).append(" instanceof ").append(RecordingMap.class.getName()).append(") {\n");
                sb.append("\t\t\t((").append(RecordingMap.class.getName()).append(") $0.").append(fieldName).append(").$$_unsetParent();\n");
                sb.append("\t\t}\n");
            } else {
                sb.append("\t\tif ($0.").append(fieldName).append(" instanceof ").append(RecordingCollection.class.getName()).append(") {\n");
                sb.append("\t\t\t((").append(RecordingCollection.class.getName()).append(") $0.").append(fieldName).append(").$$_unsetParent();\n");
                sb.append("\t\t}\n");
            }
            sb.append("\t}\n");
        } else if (attribute.isSubview()) {
            if (attribute.isUpdatableOnly() && !attribute.isCorrelated()) {
                sb.append("\tif ($0.").append(fieldName).append(" != $1 && $0.").append(fieldName).append(" instanceof ").append(MutableStateTrackable.class.getName()).append(") {\n");
                sb.append("\t\t\t((").append(MutableStateTrackable.class.getName()).append(") $0.").append(fieldName).append(").$$_removeReadOnlyParent($0, ").append(mutableStateIndex).append(");\n");
                sb.append("\t} else if ($0.").append(fieldName).append(" != $1 && $0.").append(fieldName).append(" instanceof ").append(BasicDirtyTracker.class.getName()).append(") {\n");
                sb.append("\t\t\t((").append(BasicDirtyTracker.class.getName()).append(") $0.").append(fieldName).append(").$$_unsetParent();\n");
            } else {
                sb.append("\tif ($0.").append(fieldName).append(" != $1 && $0.").append(fieldName).append(" instanceof ").append(BasicDirtyTracker.class.getName()).append(") {\n");
                sb.append("\t\t((").append(BasicDirtyTracker.class.getName()).append(") $0.").append(fieldName).append(").$$_unsetParent();\n");
            }
            sb.append("\t}\n");
        }
        if (mutableStateField != null) {
            // this.mutableState[mutableStateIndex] = $1
            sb.append("\t$0.").append(mutableStateField.getName()).append("[").append(mutableStateIndex).append("] = ");
            renderValueForArray(sb, attributeField.getType(), "$1");
        }
        if (dirtyChecking) {
            // this.dirty = true
            sb.append("\t$0.$$_markDirty(").append(mutableStateIndex).append(");\n");
            // Set new objects parent
            if (attribute.isCollection() || attribute.isSubview()) {
                sb.append("\tif ($0.$$_initialized && $1 != null && $0.").append(fieldName).append(" != $1) {\n");
                if (attribute.isCollection()) {
                    if (attribute instanceof MapAttribute<?, ?, ?>) {
                        sb.append("\t\tif ($1 instanceof ").append(RecordingMap.class.getName()).append(") {\n");
                        sb.append("\t\t\t((").append(RecordingMap.class.getName()).append(") $1).$$_setParent($0, ").append(mutableStateIndex).append(");\n");
                        sb.append("\t\t}\n");
                    } else {
                        sb.append("\t\tif ($1 instanceof ").append(RecordingCollection.class.getName()).append(") {\n");
                        sb.append("\t\t\t((").append(RecordingCollection.class.getName()).append(") $1).$$_setParent($0, ").append(mutableStateIndex).append(");\n");
                        sb.append("\t\t}\n");
                    }
                } else if (attribute.isSubview()) {
                    // Correlated attributes are treated special, we don't consider correlated attributes read-only parents
                    if (attribute.isUpdatableOnly() && !attribute.isCorrelated()) {
                        sb.append("\t\tif ($1 instanceof ").append(MutableStateTrackable.class.getName()).append(") {\n");
                        sb.append("\t\t\t((").append(MutableStateTrackable.class.getName()).append(") $1).$$_addReadOnlyParent($0, ").append(mutableStateIndex).append(");\n");
                        sb.append("\t\t} else if ($1 instanceof ").append(BasicDirtyTracker.class.getName()).append(") {\n");
                        sb.append("\t\t\t((").append(BasicDirtyTracker.class.getName()).append(") $1).$$_setParent($0, ").append(mutableStateIndex).append(");\n");
                    } else {
                        sb.append("\t\tif ($1 instanceof ").append(BasicDirtyTracker.class.getName()).append(") {\n");
                        sb.append("\t\t\t((").append(BasicDirtyTracker.class.getName()).append(") $1).$$_setParent($0, ").append(mutableStateIndex).append(");\n");
                    }
                    sb.append("\t\t}\n");
                }
                sb.append("\t}\n");
            }
        }
    }
    if (!invalidSetter) {
        sb.append("\t$0.").append(fieldName).append(" = $1;\n");
    }
    sb.append('}');
    CtMethod method = CtMethod.make(minfo, cc);
    method.setBody(sb.toString());
    cc.addMethod(method);
    return method;
}
Also used : ConstPool(javassist.bytecode.ConstPool) IdentifiableType(javax.persistence.metamodel.IdentifiableType) MutableStateTrackable(com.blazebit.persistence.view.spi.type.MutableStateTrackable) BasicTypeImpl(com.blazebit.persistence.view.impl.metamodel.BasicTypeImpl) BasicDirtyTracker(com.blazebit.persistence.view.spi.type.BasicDirtyTracker) SingularAttribute(com.blazebit.persistence.view.metamodel.SingularAttribute) MapAttribute(com.blazebit.persistence.view.metamodel.MapAttribute) MethodInfo(javassist.bytecode.MethodInfo) FieldInfo(javassist.bytecode.FieldInfo) FlatViewType(com.blazebit.persistence.view.metamodel.FlatViewType) ManagedViewType(com.blazebit.persistence.view.metamodel.ManagedViewType) ViewType(com.blazebit.persistence.view.metamodel.ViewType) FlatViewType(com.blazebit.persistence.view.metamodel.FlatViewType) CtMethod(javassist.CtMethod)

Example 2 with BasicTypeImpl

use of com.blazebit.persistence.view.impl.metamodel.BasicTypeImpl 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 3 with BasicTypeImpl

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

the class EntityViewUpdaterImpl method createIdFlusher.

public static DirtyAttributeFlusher<?, Object, Object> createIdFlusher(EntityViewManagerImpl evm, Map<Object, EntityViewUpdaterImpl> localCache, ViewType<?> viewType, ViewToEntityMapper viewToEntityMapper, AbstractMethodAttribute<?, ?> idAttribute) {
    String attributeName = idAttribute.getName();
    String attributeMapping = idAttribute.getMapping();
    AttributeAccessor viewAttributeAccessor = Accessors.forViewAttribute(evm, idAttribute, true);
    AttributeAccessor entityAttributeAccessor = Accessors.forEntityMapping(evm, idAttribute);
    CompositeAttributeFlusher nestedFlusher = viewToEntityMapper != null ? (CompositeAttributeFlusher) viewToEntityMapper.getFullGraphNode() : null;
    boolean supportsQueryFlush = nestedFlusher == null || nestedFlusher.supportsQueryFlush() && evm.getJpaProvider().supportsUpdateSetEmbeddable();
    String parameterName;
    String updateFragment;
    if (supportsQueryFlush) {
        parameterName = attributeName;
        updateFragment = attributeMapping;
    } else {
        parameterName = attributeName + "_";
        updateFragment = attributeMapping + ".";
    }
    if (idAttribute.isSubview()) {
        if (viewToEntityMapper == null) {
            return null;
        }
        return new EmbeddableAttributeFlusher<>(attributeName, attributeMapping, updateFragment, parameterName, false, false, supportsQueryFlush, entityAttributeAccessor, viewAttributeAccessor, (EmbeddableUpdaterBasedViewToEntityMapper) viewToEntityMapper);
    } else {
        BasicTypeImpl<?> type = (BasicTypeImpl<?>) ((com.blazebit.persistence.view.metamodel.SingularAttribute<?, ?>) idAttribute).getType();
        // If the id is an embedded id, we need to flush individual components for subviews, so we need to determine the component flushers
        Map.Entry<AttributeAccessor, BasicAttributeFlusher>[] componentFlusherEntries = null;
        if (type.isJpaManaged()) {
            Set<Attribute<?, ?>> attributes = (Set) type.getManagedType().getAttributes();
            Map<AttributeAccessor, BasicAttributeFlusher> componentFlushers = new HashMap<>(attributes.size());
            buildComponentFlushers(evm, viewType.getEntityClass(), type.getJavaType(), attributeName + "_", attributeMapping + ".", "", attributes, componentFlushers);
            componentFlusherEntries = componentFlushers.entrySet().toArray(new Map.Entry[componentFlushers.size()]);
        }
        TypeDescriptor typeDescriptor = TypeDescriptor.forType(evm, localCache, null, idAttribute, type, null, null);
        return new BasicAttributeFlusher<>(attributeName, attributeMapping, true, false, true, false, false, false, componentFlusherEntries, typeDescriptor, updateFragment, parameterName, entityAttributeAccessor, viewAttributeAccessor, null, null, null);
    }
}
Also used : CompositeAttributeFlusher(com.blazebit.persistence.view.impl.update.flush.CompositeAttributeFlusher) 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) HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap) BasicTypeImpl(com.blazebit.persistence.view.impl.metamodel.BasicTypeImpl) TypeDescriptor(com.blazebit.persistence.view.impl.update.flush.TypeDescriptor) EmbeddableAttributeFlusher(com.blazebit.persistence.view.impl.update.flush.EmbeddableAttributeFlusher) 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)

Aggregations

BasicTypeImpl (com.blazebit.persistence.view.impl.metamodel.BasicTypeImpl)3 MapAttribute (com.blazebit.persistence.view.metamodel.MapAttribute)3 ExtendedAttribute (com.blazebit.persistence.spi.ExtendedAttribute)2 AttributeAccessor (com.blazebit.persistence.view.impl.accessor.AttributeAccessor)2 InitialValueAttributeAccessor (com.blazebit.persistence.view.impl.accessor.InitialValueAttributeAccessor)2 AbstractMethodAttribute (com.blazebit.persistence.view.impl.metamodel.AbstractMethodAttribute)2 BasicAttributeFlusher (com.blazebit.persistence.view.impl.update.flush.BasicAttributeFlusher)2 CompositeAttributeFlusher (com.blazebit.persistence.view.impl.update.flush.CompositeAttributeFlusher)2 EmbeddableAttributeFlusher (com.blazebit.persistence.view.impl.update.flush.EmbeddableAttributeFlusher)2 TypeDescriptor (com.blazebit.persistence.view.impl.update.flush.TypeDescriptor)2 ManagedViewType (com.blazebit.persistence.view.metamodel.ManagedViewType)2 MappingAttribute (com.blazebit.persistence.view.metamodel.MappingAttribute)2 MethodAttribute (com.blazebit.persistence.view.metamodel.MethodAttribute)2 PluralAttribute (com.blazebit.persistence.view.metamodel.PluralAttribute)2 ViewType (com.blazebit.persistence.view.metamodel.ViewType)2 HashMap (java.util.HashMap)2 HashSet (java.util.HashSet)2 LinkedHashMap (java.util.LinkedHashMap)2 Set (java.util.Set)2 Attribute (javax.persistence.metamodel.Attribute)2