Search in sources :

Example 6 with PluralAttributeMapping

use of org.hibernate.metamodel.mapping.PluralAttributeMapping in project hibernate-orm by hibernate.

the class StandardEntityGraphTraversalStateImpl method traverse.

@Override
public TraversalResult traverse(FetchParent fetchParent, Fetchable fetchable, boolean exploreKeySubgraph) {
    assert !(fetchable instanceof CollectionPart);
    final GraphImplementor previousContextRoot = currentGraphContext;
    AttributeNodeImplementor attributeNode = null;
    if (appliesTo(fetchParent)) {
        attributeNode = currentGraphContext.findAttributeNode(fetchable.getFetchableName());
    }
    currentGraphContext = null;
    FetchTiming fetchTiming = null;
    boolean joined = false;
    if (attributeNode != null) {
        fetchTiming = FetchTiming.IMMEDIATE;
        joined = true;
        final Map<Class<?>, SubGraphImplementor> subgraphMap;
        final Class<?> subgraphMapKey;
        if (fetchable instanceof PluralAttributeMapping) {
            PluralAttributeMapping pluralAttributeMapping = (PluralAttributeMapping) fetchable;
            assert exploreKeySubgraph && isJpaMapCollectionType(pluralAttributeMapping) || !exploreKeySubgraph && !isJpaMapCollectionType(pluralAttributeMapping);
            if (exploreKeySubgraph) {
                subgraphMap = attributeNode.getKeySubGraphMap();
                subgraphMapKey = getEntityCollectionPartJavaClass(pluralAttributeMapping.getIndexDescriptor());
            } else {
                subgraphMap = attributeNode.getSubGraphMap();
                subgraphMapKey = getEntityCollectionPartJavaClass(pluralAttributeMapping.getElementDescriptor());
            }
        } else {
            assert !exploreKeySubgraph;
            subgraphMap = attributeNode.getSubGraphMap();
            subgraphMapKey = fetchable.getJavaType().getJavaTypeClass();
        }
        if (subgraphMap != null && subgraphMapKey != null) {
            currentGraphContext = subgraphMap.get(subgraphMapKey);
        }
    }
    if (fetchTiming == null) {
        if (graphSemantic == GraphSemantic.FETCH) {
            fetchTiming = FetchTiming.DELAYED;
            joined = false;
        } else {
            fetchTiming = fetchable.getMappedFetchOptions().getTiming();
            joined = fetchable.getMappedFetchOptions().getStyle() == FetchStyle.JOIN;
        }
    }
    return new TraversalResult(previousContextRoot, fetchTiming, joined);
}
Also used : AttributeNodeImplementor(org.hibernate.graph.spi.AttributeNodeImplementor) FetchTiming(org.hibernate.engine.FetchTiming) PluralAttributeMapping(org.hibernate.metamodel.mapping.PluralAttributeMapping) EntityCollectionPart(org.hibernate.metamodel.mapping.internal.EntityCollectionPart) CollectionPart(org.hibernate.metamodel.mapping.CollectionPart) RootGraphImplementor(org.hibernate.graph.spi.RootGraphImplementor) GraphImplementor(org.hibernate.graph.spi.GraphImplementor) SubGraphImplementor(org.hibernate.graph.spi.SubGraphImplementor) SubGraphImplementor(org.hibernate.graph.spi.SubGraphImplementor)

Example 7 with PluralAttributeMapping

use of org.hibernate.metamodel.mapping.PluralAttributeMapping in project hibernate-orm by hibernate.

the class FetchMementoHbmStandard method resolve.

@Override
public FetchBuilder resolve(Parent parent, Consumer<String> querySpaceConsumer, ResultSetMappingResolutionContext context) {
    final Map<String, FetchBuilder> fetchBuilderMap = new HashMap<>();
    fetchMementoMap.forEach((attrName, fetchMemento) -> fetchBuilderMap.put(attrName, fetchMemento.resolve(this, querySpaceConsumer, context)));
    final DynamicResultBuilderEntityStandard resultBuilder;
    if (fetchable instanceof PluralAttributeMapping) {
        resultBuilder = new DynamicResultBuilderEntityStandard((EntityMappingType) ((PluralAttributeMapping) fetchable).getElementDescriptor().getPartMappingType(), tableAlias, navigablePath);
        FetchBuilder element = fetchBuilderMap.get("element");
        if (element != null) {
            if (element instanceof DynamicFetchBuilder) {
                resultBuilder.addIdColumnAliases(((DynamicFetchBuilder) element).getColumnAliases().toArray(new String[0]));
            } else {
                resultBuilder.addIdColumnAliases(((CompleteFetchBuilderEntityValuedModelPart) element).getColumnAliases().toArray(new String[0]));
            }
        }
        FetchBuilder index = fetchBuilderMap.get("index");
        if (index != null) {
            resultBuilder.addFetchBuilder(CollectionPart.Nature.INDEX.getName(), index);
        }
        for (Map.Entry<String, FetchBuilder> entry : fetchBuilderMap.entrySet()) {
            if (entry.getKey().startsWith(ELEMENT_PREFIX)) {
                resultBuilder.addFetchBuilder(entry.getKey().substring(ELEMENT_PREFIX.length()), entry.getValue());
            }
        }
    } else {
        resultBuilder = new DynamicResultBuilderEntityStandard(((ToOneAttributeMapping) fetchable).getEntityMappingType(), tableAlias, navigablePath);
        fetchBuilderMap.forEach(resultBuilder::addFetchBuilder);
    }
    return new DynamicFetchBuilderLegacy(tableAlias, ownerTableAlias, fetchable.getFetchableName(), keyColumnNames, fetchBuilderMap, resultBuilder);
}
Also used : DynamicFetchBuilder(org.hibernate.query.results.dynamic.DynamicFetchBuilder) FetchBuilder(org.hibernate.query.results.FetchBuilder) CompleteFetchBuilderEntityValuedModelPart(org.hibernate.query.results.complete.CompleteFetchBuilderEntityValuedModelPart) HashMap(java.util.HashMap) PluralAttributeMapping(org.hibernate.metamodel.mapping.PluralAttributeMapping) DynamicFetchBuilder(org.hibernate.query.results.dynamic.DynamicFetchBuilder) ToOneAttributeMapping(org.hibernate.metamodel.mapping.internal.ToOneAttributeMapping) DynamicFetchBuilderLegacy(org.hibernate.query.results.dynamic.DynamicFetchBuilderLegacy) DynamicResultBuilderEntityStandard(org.hibernate.query.results.dynamic.DynamicResultBuilderEntityStandard) EntityMappingType(org.hibernate.metamodel.mapping.EntityMappingType) HashMap(java.util.HashMap) Map(java.util.Map)

Example 8 with PluralAttributeMapping

use of org.hibernate.metamodel.mapping.PluralAttributeMapping in project hibernate-orm by hibernate.

the class AbstractCollectionPersister method selectFragment.

/**
 * Generate a list of collection index, key and element columns
 */
@Override
public String selectFragment(String alias, String columnSuffix) {
    final PluralAttributeMapping attributeMapping = getAttributeMapping();
    final QuerySpec rootQuerySpec = new QuerySpec(true);
    final LoaderSqlAstCreationState sqlAstCreationState = new LoaderSqlAstCreationState(rootQuerySpec, new SqlAliasBaseManager(), new SimpleFromClauseAccessImpl(), LockOptions.NONE, (fetchParent, querySpec, creationState) -> new ArrayList<>(), true, getFactory());
    final NavigablePath entityPath = new NavigablePath(attributeMapping.getRootPathName());
    final TableGroup rootTableGroup = attributeMapping.createRootTableGroup(true, entityPath, null, () -> p -> {
    }, new SqlAliasBaseConstant(alias), sqlAstCreationState.getSqlExpressionResolver(), sqlAstCreationState.getFromClauseAccess(), getFactory());
    rootQuerySpec.getFromClause().addRoot(rootTableGroup);
    sqlAstCreationState.getFromClauseAccess().registerTableGroup(entityPath, rootTableGroup);
    attributeMapping.createDomainResult(entityPath, rootTableGroup, null, sqlAstCreationState);
    // Wrap expressions with aliases
    final SelectClause selectClause = rootQuerySpec.getSelectClause();
    final java.util.List<SqlSelection> sqlSelections = selectClause.getSqlSelections();
    int i = 0;
    for (String keyAlias : keyColumnAliases) {
        sqlSelections.set(i, new SqlSelectionImpl(i, i + 1, new AliasedExpression(sqlSelections.get(i).getExpression(), keyAlias + columnSuffix)));
        i++;
    }
    if (hasIndex) {
        for (String indexAlias : indexColumnAliases) {
            sqlSelections.set(i, new SqlSelectionImpl(i, i + 1, new AliasedExpression(sqlSelections.get(i).getExpression(), indexAlias + columnSuffix)));
            i++;
        }
    }
    if (hasIdentifier) {
        sqlSelections.set(i, new SqlSelectionImpl(i, i + 1, new AliasedExpression(sqlSelections.get(i).getExpression(), identifierColumnAlias + columnSuffix)));
        i++;
    }
    for (int columnIndex = 0; i < sqlSelections.size(); i++, columnIndex++) {
        final SqlSelection sqlSelection = sqlSelections.get(i);
        sqlSelections.set(i, new SqlSelectionImpl(sqlSelection.getValuesArrayPosition(), sqlSelection.getJdbcResultSetIndex(), new AliasedExpression(sqlSelection.getExpression(), elementColumnAliases[columnIndex] + columnSuffix)));
    }
    final String sql = getFactory().getJdbcServices().getDialect().getSqlAstTranslatorFactory().buildSelectTranslator(getFactory(), new SelectStatement(rootQuerySpec)).translate(null, QueryOptions.NONE).getSql();
    final int fromIndex = sql.lastIndexOf(" from");
    final String expression;
    if (fromIndex != -1) {
        expression = sql.substring("select ".length(), fromIndex);
    } else {
        expression = sql.substring("select ".length());
    }
    return expression;
}
Also used : SelectClause(org.hibernate.sql.ast.tree.select.SelectClause) NavigablePath(org.hibernate.query.spi.NavigablePath) TableGroup(org.hibernate.sql.ast.tree.from.TableGroup) PluralAttributeMapping(org.hibernate.metamodel.mapping.PluralAttributeMapping) SimpleFromClauseAccessImpl(org.hibernate.sql.ast.spi.SimpleFromClauseAccessImpl) SqlAliasBaseManager(org.hibernate.sql.ast.spi.SqlAliasBaseManager) SqlAliasBaseConstant(org.hibernate.sql.ast.spi.SqlAliasBaseConstant) SqlSelection(org.hibernate.sql.ast.spi.SqlSelection) AliasedExpression(org.hibernate.sql.ast.tree.expression.AliasedExpression) SelectStatement(org.hibernate.sql.ast.tree.select.SelectStatement) LoaderSqlAstCreationState(org.hibernate.loader.ast.internal.LoaderSqlAstCreationState) SqlSelectionImpl(org.hibernate.sql.results.internal.SqlSelectionImpl) QuerySpec(org.hibernate.sql.ast.tree.select.QuerySpec)

Example 9 with PluralAttributeMapping

use of org.hibernate.metamodel.mapping.PluralAttributeMapping in project hibernate-orm by hibernate.

the class ColumnReference method getTableReference.

TableReference getTableReference(TableGroup tableGroup) {
    ModelPartContainer modelPart = tableGroup.getModelPart();
    if (modelPart instanceof PluralAttributeMapping) {
        final PluralAttributeMapping pluralAttribute = (PluralAttributeMapping) modelPart;
        if (!pluralAttribute.getCollectionDescriptor().hasManyToManyOrdering()) {
            return tableGroup.getPrimaryTableReference();
        }
        final MappingType elementMappingType = pluralAttribute.getElementDescriptor().getPartMappingType();
        if (elementMappingType instanceof AbstractEntityPersister) {
            final AbstractEntityPersister abstractEntityPersister = (AbstractEntityPersister) elementMappingType;
            final int tableNumber = abstractEntityPersister.determineTableNumberForColumn(columnExpression);
            final String tableName = abstractEntityPersister.getTableName(tableNumber);
            return tableGroup.getTableReference(tableGroup.getNavigablePath(), tableName);
        } else {
            return tableGroup.getPrimaryTableReference();
        }
    }
    return null;
}
Also used : MappingType(org.hibernate.metamodel.mapping.MappingType) PluralAttributeMapping(org.hibernate.metamodel.mapping.PluralAttributeMapping) ModelPartContainer(org.hibernate.metamodel.mapping.ModelPartContainer) AbstractEntityPersister(org.hibernate.persister.entity.AbstractEntityPersister)

Example 10 with PluralAttributeMapping

use of org.hibernate.metamodel.mapping.PluralAttributeMapping in project hibernate-orm by hibernate.

the class ResultsHelper method finalizeCollectionLoading.

public static void finalizeCollectionLoading(PersistenceContext persistenceContext, CollectionPersister collectionDescriptor, PersistentCollection<?> collectionInstance, Object key, boolean hasNoQueuedAdds) {
    CollectionEntry collectionEntry = persistenceContext.getCollectionEntry(collectionInstance);
    if (collectionEntry == null) {
        collectionEntry = persistenceContext.addInitializedCollection(collectionDescriptor, collectionInstance, key);
    } else {
        collectionEntry.postInitialize(collectionInstance);
    }
    if (collectionDescriptor.getCollectionType().hasHolder()) {
        // in case of PersistentArrayHolder we have to realign the EntityEntry loaded state with
        // the entity values
        final Object owner = collectionInstance.getOwner();
        final EntityEntry entry = persistenceContext.getEntry(owner);
        final PluralAttributeMapping mapping = collectionDescriptor.getAttributeMapping();
        final int propertyIndex = mapping.getStateArrayPosition();
        final Object[] loadedState = entry.getLoadedState();
        loadedState[propertyIndex] = mapping.getValue(owner);
        persistenceContext.addCollectionHolder(collectionInstance);
    }
    final BatchFetchQueue batchFetchQueue = persistenceContext.getBatchFetchQueue();
    batchFetchQueue.removeBatchLoadableCollection(collectionEntry);
    final SharedSessionContractImplementor session = persistenceContext.getSession();
    // add to cache if:
    final boolean addToCache = // there were no queued additions
    hasNoQueuedAdds && // and the role has a cache
    collectionDescriptor.hasCache() && // and this is not a forced initialization during flush
    session.getCacheMode().isPutEnabled() && !collectionEntry.isDoremove();
    if (addToCache) {
        addCollectionToCache(persistenceContext, collectionDescriptor, collectionInstance, key);
    }
    if (LOG.isDebugEnabled()) {
        LOG.debugf("Collection fully initialized: %s", MessageHelper.collectionInfoString(collectionDescriptor, collectionInstance, key, session));
    }
    final StatisticsImplementor statistics = session.getFactory().getStatistics();
    if (statistics.isStatisticsEnabled()) {
        statistics.loadCollection(collectionDescriptor.getRole());
    }
// todo (6.0) : there is other logic still needing to be implemented here.  caching, etc
// see org.hibernate.engine.loading.internal.CollectionLoadContext#endLoadingCollection in 5.x
}
Also used : EntityEntry(org.hibernate.engine.spi.EntityEntry) CollectionEntry(org.hibernate.engine.spi.CollectionEntry) PluralAttributeMapping(org.hibernate.metamodel.mapping.PluralAttributeMapping) SharedSessionContractImplementor(org.hibernate.engine.spi.SharedSessionContractImplementor) StatisticsImplementor(org.hibernate.stat.spi.StatisticsImplementor) BatchFetchQueue(org.hibernate.engine.spi.BatchFetchQueue)

Aggregations

PluralAttributeMapping (org.hibernate.metamodel.mapping.PluralAttributeMapping)40 TableGroup (org.hibernate.sql.ast.tree.from.TableGroup)23 NavigablePath (org.hibernate.query.spi.NavigablePath)16 PluralTableGroup (org.hibernate.sql.ast.tree.from.PluralTableGroup)15 ArrayList (java.util.ArrayList)12 QuerySpec (org.hibernate.sql.ast.tree.select.QuerySpec)12 TableGroupJoin (org.hibernate.sql.ast.tree.from.TableGroupJoin)11 CollectionPart (org.hibernate.metamodel.mapping.CollectionPart)9 ModelPart (org.hibernate.metamodel.mapping.ModelPart)9 CorrelatedPluralTableGroup (org.hibernate.sql.ast.tree.from.CorrelatedPluralTableGroup)9 CorrelatedTableGroup (org.hibernate.sql.ast.tree.from.CorrelatedTableGroup)9 LazyTableGroup (org.hibernate.sql.ast.tree.from.LazyTableGroup)9 QueryPartTableGroup (org.hibernate.sql.ast.tree.from.QueryPartTableGroup)9 VirtualTableGroup (org.hibernate.sql.ast.tree.from.VirtualTableGroup)9 SelectStatement (org.hibernate.sql.ast.tree.select.SelectStatement)9 FetchTiming (org.hibernate.engine.FetchTiming)7 SessionFactoryImplementor (org.hibernate.engine.spi.SessionFactoryImplementor)7 SqlAstQueryPartProcessingStateImpl (org.hibernate.query.sqm.sql.internal.SqlAstQueryPartProcessingStateImpl)7 SqlSelectionImpl (org.hibernate.sql.results.internal.SqlSelectionImpl)7 Map (java.util.Map)6