Search in sources :

Example 1 with ViewTypeImplementor

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

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

the class EntityViewSettingHelper method getQueryBuilder.

private static <T, Q extends FullQueryBuilder<T, Q>> Q getQueryBuilder(EntityViewSetting<T, Q> setting, CriteriaBuilder<?> criteriaBuilder, String entityViewRoot, ManagedViewTypeImplementor<?> managedView, Map<String, Object> properties) {
    if (setting.isPaginated()) {
        KeysetPage keysetPage = setting.getKeysetPage();
        boolean forceUseKeyset = keysetPage != null && getBooleanProperty(properties, ConfigurationProperties.PAGINATION_FORCE_USE_KEYSET, false);
        if (forceUseKeyset) {
            setting.withKeysetPage(null);
        }
        PaginatedCriteriaBuilder<?> builder;
        if (managedView instanceof FlatViewType<?>) {
            if (setting.isKeysetPaginated()) {
                if (setting.getFirstResult() == -1) {
                    builder = criteriaBuilder.pageAndNavigate(setting.getEntityId(), setting.getMaxResults()).withKeysetExtraction(true);
                } else {
                    builder = criteriaBuilder.page(setting.getKeysetPage(), setting.getFirstResult(), setting.getMaxResults());
                }
            } else {
                if (setting.getFirstResult() == -1) {
                    builder = criteriaBuilder.page(0, setting.getMaxResults());
                } else {
                    builder = criteriaBuilder.page(setting.getFirstResult(), setting.getMaxResults());
                }
            }
        } else {
            // When the result should be paginated, we have to properly paginate by the identifier of the view
            MethodAttribute<?, ?> idAttribute = ((ViewTypeImplementor<?>) managedView).getIdAttribute();
            String firstExpression;
            List<String> expressions;
            if (idAttribute.isSubview()) {
                String prefix = getMapping(entityViewRoot, idAttribute, criteriaBuilder);
                ManagedViewTypeImplementor<?> type = (ManagedViewTypeImplementor<?>) ((SingularAttribute<?, ?>) idAttribute).getType();
                Set<MethodAttribute<?, ?>> attributes = (Set) type.getAttributes();
                Iterator<MethodAttribute<?, ?>> iterator = attributes.iterator();
                firstExpression = getMapping(prefix, iterator.next(), criteriaBuilder);
                if (iterator.hasNext()) {
                    expressions = new ArrayList<>(attributes.size() - 1);
                    while (iterator.hasNext()) {
                        expressions.add(getMapping(prefix, iterator.next(), criteriaBuilder));
                    }
                } else {
                    expressions = null;
                }
            } else {
                expressions = null;
                firstExpression = getMapping(entityViewRoot, idAttribute, criteriaBuilder);
            }
            if (setting.isKeysetPaginated()) {
                if (setting.getFirstResult() == -1) {
                    builder = criteriaBuilder.pageByAndNavigate(setting.getEntityId(), setting.getMaxResults(), firstExpression, getExpressionArray(expressions)).withKeysetExtraction(true);
                } else {
                    builder = criteriaBuilder.pageBy(setting.getKeysetPage(), setting.getFirstResult(), setting.getMaxResults(), firstExpression, getExpressionArray(expressions));
                }
            } else {
                if (setting.getFirstResult() == -1) {
                    builder = criteriaBuilder.pageBy(0, setting.getMaxResults(), firstExpression, getExpressionArray(expressions));
                } else {
                    builder = criteriaBuilder.pageBy(setting.getFirstResult(), setting.getMaxResults(), firstExpression, getExpressionArray(expressions));
                }
            }
        }
        if (forceUseKeyset) {
            if (keysetPage.getLowest() != null) {
                builder.beforeKeyset(keysetPage.getLowest());
            } else if (keysetPage.getHighest() != null) {
                builder.afterKeyset(keysetPage.getHighest());
            }
        }
        boolean disableCountQuery = getBooleanProperty(properties, ConfigurationProperties.PAGINATION_DISABLE_COUNT_QUERY, false);
        if (disableCountQuery) {
            builder.withCountQuery(false);
        } else {
            Integer boundedCount = null;
            Object o = properties.get(ConfigurationProperties.PAGINATION_BOUNDED_COUNT);
            if (o != null) {
                if (o instanceof Integer || o instanceof Long) {
                    boundedCount = ((Number) o).intValue();
                } else if (o instanceof String) {
                    boundedCount = Integer.parseInt((String) o);
                } else {
                    throw new IllegalArgumentException("Invalid value of type " + o.getClass().getName() + " given for the integer property: " + ConfigurationProperties.PAGINATION_BOUNDED_COUNT);
                }
            }
            if (boundedCount != null) {
                builder.withBoundedCount(boundedCount);
            }
        }
        Integer highestKeyOffset = null;
        Object o = properties.get(ConfigurationProperties.PAGINATION_HIGHEST_KEYSET_OFFSET);
        if (o != null) {
            if (o instanceof Integer) {
                highestKeyOffset = ((Number) o).intValue();
            } else if (o instanceof String) {
                highestKeyOffset = Integer.parseInt((String) o);
            } else {
                throw new IllegalArgumentException("Invalid value of type " + o.getClass().getName() + " given for the integer property: " + ConfigurationProperties.PAGINATION_HIGHEST_KEYSET_OFFSET);
            }
        }
        if (highestKeyOffset != null) {
            builder.withHighestKeysetOffset(highestKeyOffset);
        }
        boolean extractAllKeysets = getBooleanProperty(properties, ConfigurationProperties.PAGINATION_EXTRACT_ALL_KEYSETS, false);
        if (extractAllKeysets) {
            builder.withExtractAllKeysets(true);
        }
        return (Q) builder;
    } else {
        return (Q) criteriaBuilder;
    }
}
Also used : ViewTypeImplementor(com.blazebit.persistence.view.impl.metamodel.ViewTypeImplementor) ManagedViewTypeImplementor(com.blazebit.persistence.view.impl.metamodel.ManagedViewTypeImplementor) HashSet(java.util.HashSet) Set(java.util.Set) MethodAttribute(com.blazebit.persistence.view.metamodel.MethodAttribute) AbstractMethodAttribute(com.blazebit.persistence.view.impl.metamodel.AbstractMethodAttribute) ManagedViewTypeImplementor(com.blazebit.persistence.view.impl.metamodel.ManagedViewTypeImplementor) KeysetPage(com.blazebit.persistence.KeysetPage) FlatViewType(com.blazebit.persistence.view.metamodel.FlatViewType)

Example 3 with ViewTypeImplementor

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

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

the class ProxyFactory method createEquals.

private CtMethod createEquals(ManagedViewTypeImplementor<?> managedViewType, CtClass cc, boolean idBased, CtField[] fields) throws NotFoundException, CannotCompileException {
    ConstPool cp = cc.getClassFile2().getConstPool();
    MethodInfo method = new MethodInfo(cp, "equals", getEqualsDesc());
    method.setAccessFlags(AccessFlag.PUBLIC);
    CtMethod m = CtMethod.make(method, cc);
    StringBuilder sb = new StringBuilder();
    sb.append('{');
    sb.append("\tif ($0 == $1) { return true; }\n");
    Class<?> viewClass = managedViewType.getJavaType();
    if (idBased) {
        sb.append("\tif ($1 == null || $0.$$_getId() == null) { return false; }\n");
        sb.append("\tif ($1 instanceof ").append(EntityViewProxy.class.getName()).append(") {\n");
        sb.append("\t\tif ($0.$$_getJpaManagedBaseClass() == ((").append(EntityViewProxy.class.getName()).append(") $1).$$_getJpaManagedBaseClass() && ");
        sb.append("$0.$$_getId().equals(((").append(EntityViewProxy.class.getName()).append(") $1).$$_getId())) {\n");
        sb.append("\t\t\treturn true;\n");
        sb.append("\t\t} else {\n");
        sb.append("\t\t\treturn false;\n");
        sb.append("\t\t}\n");
        sb.append("\t}\n");
        ViewTypeImplementor<?> viewType = (ViewTypeImplementor<?>) managedViewType;
        MethodAttribute<?, ?> idAttribute = viewType.getIdAttribute();
        if (viewType.supportsUserTypeEquals()) {
            String wrap;
            Class<?> javaType = idAttribute.getJavaType();
            if (javaType.isPrimitive()) {
                if (javaType == long.class) {
                    wrap = "Long.valueOf";
                } else if (javaType == float.class) {
                    wrap = "Float.valueOf";
                } else if (javaType == double.class) {
                    wrap = "Double.valueOf";
                } else if (javaType == short.class) {
                    wrap = "Short.valueOf";
                } else if (javaType == byte.class) {
                    wrap = "Byte.valueOf";
                } else if (javaType == boolean.class) {
                    wrap = "Boolean.valueOf";
                } else if (javaType == char.class) {
                    wrap = "Character.valueOf";
                } else {
                    wrap = "Integer.valueOf";
                }
            } else {
                wrap = "";
            }
            sb.append("\tif ($1 instanceof ").append(viewClass.getName()).append(" && $0.$$_getId().equals(").append(wrap).append("(((").append(viewClass.getName()).append(") $1).get");
            StringUtils.addFirstToUpper(sb, idAttribute.getName()).append("()))) {\n");
            sb.append("\t\t\treturn true;\n");
            sb.append("\t\t} else {\n");
            sb.append("\t\t\treturn false;\n");
            sb.append("\t\t}\n");
        } else if (viewType.supportsInterfaceEquals()) {
            sb.append("\t\tthrow new IllegalArgumentException(\"The view class ").append(viewClass.getName()).append(" is defined for an abstract or non-entity type which is why id-based equality can't be checked on the user provided instance: \" + $1);\n");
        } else {
            sb.append("\t\tthrow new IllegalArgumentException(\"A superclass of ").append(viewClass.getName()).append(" declares a protected or default attribute that is relevant for checking for state equality which can't be accessed on the user provided instance: \" + $1);\n");
        }
    } else {
        String name;
        if (managedViewType.supportsInterfaceEquals()) {
            name = viewClass.getName();
        } else {
            name = cc.getName();
        }
        sb.append("\tif ($1 instanceof ").append(name).append(") {\n");
        sb.append("\t\tfinal ").append(name).append(" other = (").append(name).append(") $1;\n");
        for (CtField field : fields) {
            if (field.getType().isPrimitive()) {
                if (CtClass.booleanType == field.getType() && managedViewType.getAttribute(field.getName()).getJavaMethod().getName().startsWith("is")) {
                    sb.append("\t\tif ($0.").append(field.getName()).append(" != other.is");
                    StringUtils.addFirstToUpper(sb, field.getName()).append("()");
                    sb.append(") {\n");
                } else {
                    sb.append("\t\tif ($0.").append(field.getName()).append(" != other.get");
                    StringUtils.addFirstToUpper(sb, field.getName()).append("()");
                    sb.append(") {\n");
                }
            } else {
                if (Boolean.class.getName().equals(field.getType().getName()) && managedViewType.getAttribute(field.getName()).getJavaMethod().getName().startsWith("is")) {
                    sb.append("\t\tif ($0.").append(field.getName()).append(" != other.is");
                    StringUtils.addFirstToUpper(sb, field.getName()).append("()");
                    sb.append(" && ($0.").append(field.getName()).append(" == null");
                    sb.append(" || !$0.").append(field.getName()).append(".equals(other.is");
                    StringUtils.addFirstToUpper(sb, field.getName()).append("()");
                    sb.append("))) {\n");
                } else {
                    sb.append("\t\tif ($0.").append(field.getName()).append(" != other.get");
                    StringUtils.addFirstToUpper(sb, field.getName()).append("()");
                    sb.append(" && ($0.").append(field.getName()).append(" == null");
                    sb.append(" || !$0.").append(field.getName()).append(".equals(other.get");
                    StringUtils.addFirstToUpper(sb, field.getName()).append("()");
                    sb.append("))) {\n");
                }
            }
            sb.append("\t\t\treturn false;\n\t\t}\n");
        }
        sb.append("\t} else {\n");
        if (managedViewType.supportsInterfaceEquals()) {
            sb.append("\t\treturn false;\n");
        } else {
            sb.append("\t\tif ($1 == null) { return false; }\n");
            sb.append("\t\tthrow new IllegalArgumentException(\"A superclass of ").append(viewClass.getName()).append(" declares a protected or default attribute that is relevant for checking for state equality which can't be accessed on the user provided instance: \" + $1);\n");
        }
        sb.append("\t}\n");
        sb.append("\treturn true;\n");
    }
    sb.append('}');
    m.setBody(sb.toString());
    return m;
}
Also used : ConstPool(javassist.bytecode.ConstPool) ViewTypeImplementor(com.blazebit.persistence.view.impl.metamodel.ViewTypeImplementor) ManagedViewTypeImplementor(com.blazebit.persistence.view.impl.metamodel.ManagedViewTypeImplementor) CtField(javassist.CtField) MethodInfo(javassist.bytecode.MethodInfo) CtMethod(javassist.CtMethod)

Example 5 with ViewTypeImplementor

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

the class ProxyFactory method createToString.

private CtMethod createToString(ManagedViewTypeImplementor<?> managedViewType, CtClass cc, boolean idBased, CtField[] fields) throws NotFoundException, CannotCompileException {
    ConstPool cp = cc.getClassFile2().getConstPool();
    MethodInfo method = new MethodInfo(cp, "toString", "()" + Descriptor.of("java.lang.String"));
    method.setAccessFlags(AccessFlag.PUBLIC);
    CtMethod m = CtMethod.make(method, cc);
    StringBuilder sb = new StringBuilder();
    sb.append('{');
    if (idBased) {
        ViewTypeImplementor<?> viewType = (ViewTypeImplementor<?>) managedViewType;
        MethodAttribute<?, ?> idAttribute = viewType.getIdAttribute();
        sb.append("\treturn \"").append(managedViewType.getJavaType().getSimpleName()).append("(").append(idAttribute.getName()).append(" = \" + $0.").append(idAttribute.getName()).append(" + \")\";\n");
    } else {
        int sizeEstimate = managedViewType.getJavaType().getSimpleName().length() + 2;
        for (int i = 0; i < fields.length; i++) {
            // 5 is the amount of chars for the format
            // 10 is the amount of chars that we assume is needed to represent a value on average
            sizeEstimate += fields[i].getName().length() + 5 + 10;
        }
        sb.append("\tStringBuilder sb = new StringBuilder(").append(sizeEstimate).append(");\n");
        sb.append("\tsb.append(\"").append(managedViewType.getJavaType().getSimpleName()).append("(\");\n");
        if (fields.length != 0) {
            sb.append("\tsb.append(\"").append(fields[0].getName()).append(" = \").append($0.").append(fields[0].getName()).append(");\n");
            for (int i = 1; i < fields.length; i++) {
                sb.append("\tsb.append(\", \");\n");
                sb.append("\tsb.append(\"").append(fields[i].getName()).append(" = \").append($0.").append(fields[i].getName()).append(");\n");
            }
        }
        sb.append("\tsb.append(\")\");\n");
        sb.append("\treturn sb.toString();\n");
    }
    sb.append('}');
    m.setBody(sb.toString());
    return m;
}
Also used : ConstPool(javassist.bytecode.ConstPool) ViewTypeImplementor(com.blazebit.persistence.view.impl.metamodel.ViewTypeImplementor) ManagedViewTypeImplementor(com.blazebit.persistence.view.impl.metamodel.ManagedViewTypeImplementor) MethodInfo(javassist.bytecode.MethodInfo) CtMethod(javassist.CtMethod)

Aggregations

ManagedViewTypeImplementor (com.blazebit.persistence.view.impl.metamodel.ManagedViewTypeImplementor)5 ViewTypeImplementor (com.blazebit.persistence.view.impl.metamodel.ViewTypeImplementor)5 AbstractMethodAttribute (com.blazebit.persistence.view.impl.metamodel.AbstractMethodAttribute)3 MethodAttribute (com.blazebit.persistence.view.metamodel.MethodAttribute)3 HashSet (java.util.HashSet)3 Set (java.util.Set)3 EntityMetamodel (com.blazebit.persistence.parser.EntityMetamodel)2 ExtendedAttribute (com.blazebit.persistence.spi.ExtendedAttribute)2 ExtendedManagedType (com.blazebit.persistence.spi.ExtendedManagedType)2 AttributeAccessor (com.blazebit.persistence.view.impl.accessor.AttributeAccessor)2 InitialValueAttributeAccessor (com.blazebit.persistence.view.impl.accessor.InitialValueAttributeAccessor)2 EmbeddableUpdaterBasedViewToEntityMapper (com.blazebit.persistence.view.impl.entity.EmbeddableUpdaterBasedViewToEntityMapper)2 LoadOnlyViewToEntityMapper (com.blazebit.persistence.view.impl.entity.LoadOnlyViewToEntityMapper)2 LoadOrPersistViewToEntityMapper (com.blazebit.persistence.view.impl.entity.LoadOrPersistViewToEntityMapper)2 MapViewToEntityMapper (com.blazebit.persistence.view.impl.entity.MapViewToEntityMapper)2 UpdaterBasedViewToEntityMapper (com.blazebit.persistence.view.impl.entity.UpdaterBasedViewToEntityMapper)2 ViewToEntityMapper (com.blazebit.persistence.view.impl.entity.ViewToEntityMapper)2 BasicAttributeFlusher (com.blazebit.persistence.view.impl.update.flush.BasicAttributeFlusher)2 EmbeddableAttributeFlusher (com.blazebit.persistence.view.impl.update.flush.EmbeddableAttributeFlusher)2 SimpleMapViewToEntityMapper (com.blazebit.persistence.view.impl.update.flush.SimpleMapViewToEntityMapper)2