Search in sources :

Example 6 with MappingMetamodel

use of org.hibernate.metamodel.MappingMetamodel in project hibernate-orm by hibernate.

the class CompoundNaturalIdTests method testLoad.

@Test
public void testLoad(SessionFactoryScope scope) {
    scope.inTransaction(session -> {
        final Account account = session.byNaturalId(Account.class).using("system", "matrix").using("username", "neo").load();
        verifyEntity(account);
    });
    scope.inTransaction(session -> {
        final MappingMetamodel mappingMetamodel = session.getFactory().getRuntimeMetamodels().getMappingMetamodel();
        final EntityPersister accountMapping = mappingMetamodel.findEntityDescriptor(Account.class);
        final NaturalIdMapping naturalIdMapping = accountMapping.getNaturalIdMapping();
        // test load by array
        accountMapping.getNaturalIdLoader().load(VALUE_ARRAY, NaturalIdLoadOptions.NONE, session);
        // and by Map
        accountMapping.getNaturalIdLoader().load(VALUE_NAP, NaturalIdLoadOptions.NONE, session);
    });
}
Also used : EntityPersister(org.hibernate.persister.entity.EntityPersister) MappingMetamodel(org.hibernate.metamodel.MappingMetamodel) NaturalIdMapping(org.hibernate.metamodel.mapping.NaturalIdMapping) Test(org.junit.jupiter.api.Test)

Example 7 with MappingMetamodel

use of org.hibernate.metamodel.MappingMetamodel in project hibernate-orm by hibernate.

the class CompoundNaturalIdTests method testGetReference.

@Test
public void testGetReference(SessionFactoryScope scope) {
    scope.inTransaction(session -> {
        final NaturalIdLoadAccess<Account> loadAccess = session.byNaturalId(Account.class);
        loadAccess.using("system", "matrix");
        loadAccess.using("username", "neo");
        verifyEntity(loadAccess.getReference());
    });
    scope.inTransaction(session -> {
        final MappingMetamodel mappingMetamodel = session.getFactory().getRuntimeMetamodels().getMappingMetamodel();
        final EntityPersister accountMapping = mappingMetamodel.findEntityDescriptor(Account.class);
        final NaturalIdMapping naturalIdMapping = accountMapping.getNaturalIdMapping();
        // test load by array
        Object id = accountMapping.getNaturalIdLoader().resolveNaturalIdToId(VALUE_ARRAY, session);
        assertThat(id, is(1));
        // and by Map
        id = accountMapping.getNaturalIdLoader().resolveNaturalIdToId(VALUE_NAP, session);
        assertThat(id, is(1));
    });
}
Also used : EntityPersister(org.hibernate.persister.entity.EntityPersister) MappingMetamodel(org.hibernate.metamodel.MappingMetamodel) NaturalIdMapping(org.hibernate.metamodel.mapping.NaturalIdMapping) Test(org.junit.jupiter.api.Test)

Example 8 with MappingMetamodel

use of org.hibernate.metamodel.MappingMetamodel in project hibernate-orm by hibernate.

the class SimpleNaturalIdTests method testProcessing.

@Test
public void testProcessing(DomainModelScope domainModelScope, SessionFactoryScope factoryScope) {
    final PersistentClass productBootMapping = domainModelScope.getDomainModel().getEntityBinding(Product.class.getName());
    assertThat(productBootMapping.hasNaturalId(), is(true));
    final Property sku = productBootMapping.getProperty("sku");
    assertThat(sku.isNaturalIdentifier(), is(true));
    final MappingMetamodel mappingMetamodel = factoryScope.getSessionFactory().getRuntimeMetamodels().getMappingMetamodel();
    final EntityPersister productMapping = mappingMetamodel.findEntityDescriptor(Product.class);
    assertThat(productMapping.hasNaturalIdentifier(), is(true));
    final NaturalIdMapping naturalIdMapping = productMapping.getNaturalIdMapping();
    assertThat(naturalIdMapping, notNullValue());
}
Also used : EntityPersister(org.hibernate.persister.entity.EntityPersister) MappingMetamodel(org.hibernate.metamodel.MappingMetamodel) Product(org.hibernate.testing.orm.domain.retail.Product) NaturalIdMapping(org.hibernate.metamodel.mapping.NaturalIdMapping) Property(org.hibernate.mapping.Property) PersistentClass(org.hibernate.mapping.PersistentClass) Test(org.junit.jupiter.api.Test)

Example 9 with MappingMetamodel

use of org.hibernate.metamodel.MappingMetamodel in project hibernate-orm by hibernate.

the class TableBasedUpdateHandler method resolveDelegate.

private ExecutionDelegate resolveDelegate(DomainQueryExecutionContext executionContext) {
    final SessionFactoryImplementor sessionFactory = getSessionFactory();
    final MappingMetamodel domainModel = sessionFactory.getRuntimeMetamodels().getMappingMetamodel();
    final EntityPersister entityDescriptor = domainModel.getEntityDescriptor(getSqmDeleteOrUpdateStatement().getTarget().getEntityName());
    final String rootEntityName = entityDescriptor.getRootEntityName();
    final EntityPersister rootEntityDescriptor = domainModel.getEntityDescriptor(rootEntityName);
    final String hierarchyRootTableName = ((Joinable) rootEntityDescriptor).getTableName();
    final MultiTableSqmMutationConverter converterDelegate = new MultiTableSqmMutationConverter(entityDescriptor, getSqmDeleteOrUpdateStatement(), getSqmDeleteOrUpdateStatement().getTarget(), domainParameterXref, executionContext.getQueryOptions(), executionContext.getSession().getLoadQueryInfluencers(), executionContext.getQueryParameterBindings(), sessionFactory);
    final TableGroup updatingTableGroup = converterDelegate.getMutatingTableGroup();
    final TableReference hierarchyRootTableReference = updatingTableGroup.resolveTableReference(updatingTableGroup.getNavigablePath(), hierarchyRootTableName);
    assert hierarchyRootTableReference != null;
    final Map<SqmParameter<?>, List<List<JdbcParameter>>> parameterResolutions;
    if (domainParameterXref.getSqmParameterCount() == 0) {
        parameterResolutions = Collections.emptyMap();
    } else {
        parameterResolutions = new IdentityHashMap<>();
    }
    // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    // visit the set-clause using our special converter, collecting
    // information about the assignments
    final List<Assignment> assignments = new ArrayList<>();
    final Map<SqmParameter<?>, MappingModelExpressible<?>> paramTypeResolutions = new LinkedHashMap<>();
    converterDelegate.visitSetClause(getSqmDeleteOrUpdateStatement().getSetClause(), assignments::add, (sqmParameter, mappingType, jdbcParameters) -> {
        parameterResolutions.computeIfAbsent(sqmParameter, k -> new ArrayList<>(1)).add(jdbcParameters);
        paramTypeResolutions.put(sqmParameter, mappingType);
    });
    converterDelegate.addVersionedAssignment(assignments::add, getSqmDeleteOrUpdateStatement());
    // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    // visit the where-clause using our special converter, collecting information
    // about the restrictions
    final Predicate providedPredicate;
    final SqmWhereClause whereClause = getSqmUpdate().getWhereClause();
    if (whereClause == null || whereClause.getPredicate() == null) {
        providedPredicate = null;
    } else {
        providedPredicate = converterDelegate.visitWhereClause(whereClause, columnReference -> {
        }, (sqmParameter, mappingType, jdbcParameters) -> {
            parameterResolutions.computeIfAbsent(sqmParameter, k -> new ArrayList<>(1)).add(jdbcParameters);
            paramTypeResolutions.put(sqmParameter, mappingType);
        });
        assert providedPredicate != null;
    }
    final PredicateCollector predicateCollector = new PredicateCollector(providedPredicate);
    entityDescriptor.applyBaseRestrictions(predicateCollector::applyPredicate, updatingTableGroup, true, executionContext.getSession().getLoadQueryInfluencers().getEnabledFilters(), null, converterDelegate);
    converterDelegate.pruneTableGroupJoins();
    // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    // cross-reference the TableReference by alias.  The TableGroup already
    // cross-references it by name, bu the ColumnReference only has the alias
    final Map<String, TableReference> tableReferenceByAlias = CollectionHelper.mapOfSize(updatingTableGroup.getTableReferenceJoins().size() + 1);
    collectTableReference(updatingTableGroup.getPrimaryTableReference(), tableReferenceByAlias::put);
    for (int i = 0; i < updatingTableGroup.getTableReferenceJoins().size(); i++) {
        collectTableReference(updatingTableGroup.getTableReferenceJoins().get(i), tableReferenceByAlias::put);
    }
    return new UpdateExecutionDelegate(getSqmUpdate(), converterDelegate, idTable, afterUseAction, sessionUidAccess, domainParameterXref, updatingTableGroup, hierarchyRootTableReference, tableReferenceByAlias, assignments, predicateCollector.getPredicate(), parameterResolutions, paramTypeResolutions, executionContext);
}
Also used : EntityPersister(org.hibernate.persister.entity.EntityPersister) CollectionHelper(org.hibernate.internal.util.collections.CollectionHelper) ExecutionContext(org.hibernate.sql.exec.spi.ExecutionContext) EntityPersister(org.hibernate.persister.entity.EntityPersister) PredicateCollector(org.hibernate.sql.ast.tree.predicate.PredicateCollector) Logger(org.jboss.logging.Logger) Function(java.util.function.Function) Joinable(org.hibernate.persister.entity.Joinable) ArrayList(java.util.ArrayList) SqmJdbcExecutionContextAdapter(org.hibernate.query.sqm.internal.SqmJdbcExecutionContextAdapter) TableReference(org.hibernate.sql.ast.tree.from.TableReference) LinkedHashMap(java.util.LinkedHashMap) MultiTableSqmMutationConverter(org.hibernate.query.sqm.mutation.internal.MultiTableSqmMutationConverter) Map(java.util.Map) BiConsumer(java.util.function.BiConsumer) SqmUpdateStatement(org.hibernate.query.sqm.tree.update.SqmUpdateStatement) TableReferenceJoin(org.hibernate.sql.ast.tree.from.TableReferenceJoin) SessionFactoryImplementor(org.hibernate.engine.spi.SessionFactoryImplementor) Assignment(org.hibernate.sql.ast.tree.update.Assignment) IdentityHashMap(java.util.IdentityHashMap) TemporaryTable(org.hibernate.dialect.temptable.TemporaryTable) Predicate(org.hibernate.sql.ast.tree.predicate.Predicate) DomainQueryExecutionContext(org.hibernate.query.spi.DomainQueryExecutionContext) MappingMetamodel(org.hibernate.metamodel.MappingMetamodel) List(java.util.List) JdbcParameter(org.hibernate.sql.ast.tree.expression.JdbcParameter) SqmWhereClause(org.hibernate.query.sqm.tree.predicate.SqmWhereClause) UpdateHandler(org.hibernate.query.sqm.mutation.internal.UpdateHandler) SqmParameter(org.hibernate.query.sqm.tree.expression.SqmParameter) AbstractMutationHandler(org.hibernate.query.sqm.mutation.spi.AbstractMutationHandler) DomainParameterXref(org.hibernate.query.sqm.internal.DomainParameterXref) Collections(java.util.Collections) MappingModelExpressible(org.hibernate.metamodel.mapping.MappingModelExpressible) TableGroup(org.hibernate.sql.ast.tree.from.TableGroup) SharedSessionContractImplementor(org.hibernate.engine.spi.SharedSessionContractImplementor) MappingModelExpressible(org.hibernate.metamodel.mapping.MappingModelExpressible) ArrayList(java.util.ArrayList) LinkedHashMap(java.util.LinkedHashMap) Predicate(org.hibernate.sql.ast.tree.predicate.Predicate) Assignment(org.hibernate.sql.ast.tree.update.Assignment) TableReference(org.hibernate.sql.ast.tree.from.TableReference) ArrayList(java.util.ArrayList) List(java.util.List) TableGroup(org.hibernate.sql.ast.tree.from.TableGroup) SessionFactoryImplementor(org.hibernate.engine.spi.SessionFactoryImplementor) JdbcParameter(org.hibernate.sql.ast.tree.expression.JdbcParameter) MappingMetamodel(org.hibernate.metamodel.MappingMetamodel) PredicateCollector(org.hibernate.sql.ast.tree.predicate.PredicateCollector) Joinable(org.hibernate.persister.entity.Joinable) SqmWhereClause(org.hibernate.query.sqm.tree.predicate.SqmWhereClause) SqmParameter(org.hibernate.query.sqm.tree.expression.SqmParameter) MultiTableSqmMutationConverter(org.hibernate.query.sqm.mutation.internal.MultiTableSqmMutationConverter)

Example 10 with MappingMetamodel

use of org.hibernate.metamodel.MappingMetamodel in project hibernate-orm by hibernate.

the class BasicValuedPathInterpretation method from.

/**
 * Static factory
 */
public static <T> BasicValuedPathInterpretation<T> from(SqmBasicValuedSimplePath<T> sqmPath, SqlAstCreationState sqlAstCreationState, SemanticQueryWalker sqmWalker, boolean jpaQueryComplianceEnabled) {
    final FromClauseAccess fromClauseAccess = sqlAstCreationState.getFromClauseAccess();
    final TableGroup tableGroup = fromClauseAccess.getTableGroup(sqmPath.getNavigablePath().getParent());
    EntityMappingType treatTarget = null;
    if (jpaQueryComplianceEnabled) {
        if (sqmPath.getLhs() instanceof SqmTreatedPath) {
            final EntityDomainType treatTargetDomainType = ((SqmTreatedPath) sqmPath.getLhs()).getTreatTarget();
            final MappingMetamodel mappingMetamodel = sqlAstCreationState.getCreationContext().getSessionFactory().getRuntimeMetamodels().getMappingMetamodel();
            treatTarget = mappingMetamodel.findEntityDescriptor(treatTargetDomainType.getHibernateEntityName());
        } else if (sqmPath.getLhs().getNodeType() instanceof EntityDomainType) {
            final EntityDomainType entityDomainType = (EntityDomainType) sqmPath.getLhs().getNodeType();
            final MappingMetamodel mappingMetamodel = sqlAstCreationState.getCreationContext().getSessionFactory().getRuntimeMetamodels().getMappingMetamodel();
            treatTarget = mappingMetamodel.findEntityDescriptor(entityDomainType.getHibernateEntityName());
        }
    }
    final BasicValuedModelPart mapping = (BasicValuedModelPart) tableGroup.getModelPart().findSubPart(sqmPath.getReferencedPathSource().getPathName(), treatTarget);
    if (mapping == null) {
        if (jpaQueryComplianceEnabled) {
            // to get the better error, see if we got nothing because of treat handling
            final ModelPart subPart = tableGroup.getModelPart().findSubPart(sqmPath.getReferencedPathSource().getPathName(), null);
            if (subPart != null) {
                throw new StrictJpaComplianceViolation(StrictJpaComplianceViolation.Type.IMPLICIT_TREAT);
            }
        }
        throw new SemanticException("`" + sqmPath.getNavigablePath().getFullPath() + "` did not reference a known model part");
    }
    final TableReference tableReference = tableGroup.resolveTableReference(sqmPath.getNavigablePath(), mapping.getContainingTableExpression());
    final Expression expression = sqlAstCreationState.getSqlExpressionResolver().resolveSqlExpression(SqlExpressionResolver.createColumnReferenceKey(tableReference, mapping.getSelectionExpression()), sacs -> new ColumnReference(tableReference.getIdentificationVariable(), mapping, sqlAstCreationState.getCreationContext().getSessionFactory()));
    final ColumnReference columnReference;
    if (expression instanceof ColumnReference) {
        columnReference = ((ColumnReference) expression);
    } else if (expression instanceof SqlSelectionExpression) {
        final Expression selectedExpression = ((SqlSelectionExpression) expression).getSelection().getExpression();
        assert selectedExpression instanceof ColumnReference;
        columnReference = (ColumnReference) selectedExpression;
    } else {
        throw new UnsupportedOperationException("Unsupported basic-valued path expression : " + expression);
    }
    return new BasicValuedPathInterpretation<>(columnReference, sqmPath.getNavigablePath(), mapping, tableGroup);
}
Also used : TableGroup(org.hibernate.sql.ast.tree.from.TableGroup) BasicValuedModelPart(org.hibernate.metamodel.mapping.BasicValuedModelPart) BasicValuedModelPart(org.hibernate.metamodel.mapping.BasicValuedModelPart) ModelPart(org.hibernate.metamodel.mapping.ModelPart) SqmTreatedPath(org.hibernate.query.sqm.tree.domain.SqmTreatedPath) SqlSelectionExpression(org.hibernate.sql.ast.tree.expression.SqlSelectionExpression) TableReference(org.hibernate.sql.ast.tree.from.TableReference) MappingMetamodel(org.hibernate.metamodel.MappingMetamodel) FromClauseAccess(org.hibernate.sql.ast.spi.FromClauseAccess) SqlSelectionExpression(org.hibernate.sql.ast.tree.expression.SqlSelectionExpression) Expression(org.hibernate.sql.ast.tree.expression.Expression) StrictJpaComplianceViolation(org.hibernate.query.sqm.StrictJpaComplianceViolation) EntityDomainType(org.hibernate.metamodel.model.domain.EntityDomainType) EntityMappingType(org.hibernate.metamodel.mapping.EntityMappingType) SemanticException(org.hibernate.query.SemanticException) ColumnReference(org.hibernate.sql.ast.tree.expression.ColumnReference)

Aggregations

MappingMetamodel (org.hibernate.metamodel.MappingMetamodel)25 Test (org.junit.jupiter.api.Test)13 EntityPersister (org.hibernate.persister.entity.EntityPersister)12 SessionFactoryImplementor (org.hibernate.engine.spi.SessionFactoryImplementor)7 EntityMappingType (org.hibernate.metamodel.mapping.EntityMappingType)7 PluralAttributeMapping (org.hibernate.metamodel.mapping.PluralAttributeMapping)5 TableGroup (org.hibernate.sql.ast.tree.from.TableGroup)5 ArrayList (java.util.ArrayList)4 List (java.util.List)4 Map (java.util.Map)4 PersistentClass (org.hibernate.mapping.PersistentClass)4 AttributeMapping (org.hibernate.metamodel.mapping.AttributeMapping)4 EntityDomainType (org.hibernate.metamodel.model.domain.EntityDomainType)4 QueryException (org.hibernate.QueryException)3 EmbeddableMappingType (org.hibernate.metamodel.mapping.EmbeddableMappingType)3 JdbcMapping (org.hibernate.metamodel.mapping.JdbcMapping)3 MappingModelExpressible (org.hibernate.metamodel.mapping.MappingModelExpressible)3 NaturalIdMapping (org.hibernate.metamodel.mapping.NaturalIdMapping)3 DiscriminatorSqmPath (org.hibernate.metamodel.model.domain.internal.DiscriminatorSqmPath)3 Joinable (org.hibernate.persister.entity.Joinable)3