Search in sources :

Example 1 with ForeignKeyDescriptor

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

the class MappingModelCreationHelper method setReferencedAttributeForeignKeyDescriptor.

private static void setReferencedAttributeForeignKeyDescriptor(AbstractAttributeMapping attributeMapping, ToOneAttributeMapping referencedAttributeMapping, EntityPersister referencedEntityDescriptor, String referencedPropertyName, Dialect dialect, MappingModelCreationProcess creationProcess) {
    ForeignKeyDescriptor foreignKeyDescriptor = referencedAttributeMapping.getForeignKeyDescriptor();
    if (foreignKeyDescriptor == null) {
        PersistentClass entityBinding = creationProcess.getCreationContext().getBootModel().getEntityBinding(referencedEntityDescriptor.getEntityName());
        Property property = entityBinding.getRecursiveProperty(referencedPropertyName);
        interpretToOneKeyDescriptor(referencedAttributeMapping, property, (ToOne) property.getValue(), referencedAttributeMapping.getPropertyAccess(), dialect, creationProcess);
        attributeMapping.setForeignKeyDescriptor(referencedAttributeMapping.getForeignKeyDescriptor());
    } else {
        attributeMapping.setForeignKeyDescriptor(foreignKeyDescriptor);
    }
}
Also used : ForeignKeyDescriptor(org.hibernate.metamodel.mapping.ForeignKeyDescriptor) Property(org.hibernate.mapping.Property) PersistentClass(org.hibernate.mapping.PersistentClass)

Example 2 with ForeignKeyDescriptor

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

the class AbstractCompositeIdentifierMapping method forEachJdbcValue.

@Override
public int forEachJdbcValue(Object value, Clause clause, int offset, JdbcValuesConsumer valuesConsumer, SharedSessionContractImplementor session) {
    int span = 0;
    final List<AttributeMapping> attributeMappings = getEmbeddableTypeDescriptor().getAttributeMappings();
    for (int i = 0; i < attributeMappings.size(); i++) {
        final AttributeMapping attributeMapping = attributeMappings.get(i);
        final Object o = attributeMapping.getPropertyAccess().getGetter().get(value);
        if (attributeMapping instanceof ToOneAttributeMapping) {
            final ToOneAttributeMapping toOneAttributeMapping = (ToOneAttributeMapping) attributeMapping;
            final ForeignKeyDescriptor fkDescriptor = toOneAttributeMapping.getForeignKeyDescriptor();
            final Object identifier = fkDescriptor.getAssociationKeyFromSide(o, toOneAttributeMapping.getSideNature().inverse(), session);
            span += fkDescriptor.forEachJdbcValue(identifier, clause, span + offset, valuesConsumer, session);
        } else {
            span += attributeMapping.forEachJdbcValue(o, clause, span + offset, valuesConsumer, session);
        }
    }
    return span;
}
Also used : ToOneAttributeMapping(org.hibernate.metamodel.mapping.internal.ToOneAttributeMapping) ForeignKeyDescriptor(org.hibernate.metamodel.mapping.ForeignKeyDescriptor) ToOneAttributeMapping(org.hibernate.metamodel.mapping.internal.ToOneAttributeMapping) AttributeMapping(org.hibernate.metamodel.mapping.AttributeMapping)

Example 3 with ForeignKeyDescriptor

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

the class SimpleDeleteQueryPlan method executeUpdate.

@Override
public int executeUpdate(DomainQueryExecutionContext executionContext) {
    BulkOperationCleanupAction.schedule(executionContext.getSession(), sqmDelete);
    final SharedSessionContractImplementor session = executionContext.getSession();
    final SessionFactoryImplementor factory = session.getFactory();
    final JdbcServices jdbcServices = factory.getJdbcServices();
    SqlAstTranslator<JdbcDelete> deleteTranslator = null;
    if (jdbcDelete == null) {
        deleteTranslator = createDeleteTranslator(executionContext);
    }
    final JdbcParameterBindings jdbcParameterBindings = SqmUtil.createJdbcParameterBindings(executionContext.getQueryParameterBindings(), domainParameterXref, jdbcParamsXref, factory.getRuntimeMetamodels().getMappingMetamodel(), sqmInterpretation.getFromClauseAccess()::findTableGroup, new SqmParameterMappingModelResolutionAccess() {

        @Override
        @SuppressWarnings("unchecked")
        public <T> MappingModelExpressible<T> getResolvedMappingModelType(SqmParameter<T> parameter) {
            return (MappingModelExpressible<T>) sqmInterpretation.getSqmParameterMappingModelTypeResolutions().get(parameter);
        }
    }, session);
    if (jdbcDelete != null && !jdbcDelete.isCompatibleWith(jdbcParameterBindings, executionContext.getQueryOptions())) {
        deleteTranslator = createDeleteTranslator(executionContext);
    }
    if (deleteTranslator != null) {
        jdbcDelete = deleteTranslator.translate(jdbcParameterBindings, executionContext.getQueryOptions());
    } else {
        jdbcDelete.bindFilterJdbcParameters(jdbcParameterBindings);
    }
    final boolean missingRestriction = sqmDelete.getWhereClause() == null || sqmDelete.getWhereClause().getPredicate() == null;
    if (missingRestriction) {
        assert domainParameterXref.getSqmParameterCount() == 0;
        assert jdbcParamsXref.isEmpty();
    }
    final SqmJdbcExecutionContextAdapter executionContextAdapter = SqmJdbcExecutionContextAdapter.usingLockingAndPaging(executionContext);
    SqmMutationStrategyHelper.cleanUpCollectionTables(entityDescriptor, (tableReference, attributeMapping) -> {
        if (missingRestriction) {
            return null;
        }
        final ForeignKeyDescriptor fkDescriptor = attributeMapping.getKeyDescriptor();
        final Expression fkColumnExpression = MappingModelHelper.buildColumnReferenceExpression(fkDescriptor.getKeyPart(), null, factory);
        final QuerySpec matchingIdSubQuery = new QuerySpec(false);
        final MutatingTableReferenceGroupWrapper tableGroup = new MutatingTableReferenceGroupWrapper(new NavigablePath(attributeMapping.getRootPathName()), attributeMapping, sqmInterpretation.getSqlAst().getTargetTable());
        final Expression fkTargetColumnExpression = MappingModelHelper.buildColumnReferenceExpression(tableGroup, fkDescriptor.getTargetPart(), sqmInterpretation.getSqlExpressionResolver(), factory);
        matchingIdSubQuery.getSelectClause().addSqlSelection(new SqlSelectionImpl(1, 0, fkTargetColumnExpression));
        matchingIdSubQuery.getFromClause().addRoot(tableGroup);
        matchingIdSubQuery.applyPredicate(sqmInterpretation.getSqlAst().getRestriction());
        return new InSubQueryPredicate(fkColumnExpression, matchingIdSubQuery, false);
    }, (missingRestriction ? JdbcParameterBindings.NO_BINDINGS : jdbcParameterBindings), executionContextAdapter);
    return jdbcServices.getJdbcMutationExecutor().execute(jdbcDelete, jdbcParameterBindings, sql -> session.getJdbcCoordinator().getStatementPreparer().prepareStatement(sql), (integer, preparedStatement) -> {
    }, executionContextAdapter);
}
Also used : MutatingTableReferenceGroupWrapper(org.hibernate.sql.ast.tree.from.MutatingTableReferenceGroupWrapper) NavigablePath(org.hibernate.query.spi.NavigablePath) SqmParameterMappingModelResolutionAccess(org.hibernate.query.sqm.spi.SqmParameterMappingModelResolutionAccess) MappingModelExpressible(org.hibernate.metamodel.mapping.MappingModelExpressible) SessionFactoryImplementor(org.hibernate.engine.spi.SessionFactoryImplementor) InSubQueryPredicate(org.hibernate.sql.ast.tree.predicate.InSubQueryPredicate) SharedSessionContractImplementor(org.hibernate.engine.spi.SharedSessionContractImplementor) JdbcServices(org.hibernate.engine.jdbc.spi.JdbcServices) Expression(org.hibernate.sql.ast.tree.expression.Expression) ForeignKeyDescriptor(org.hibernate.metamodel.mapping.ForeignKeyDescriptor) SqlSelectionImpl(org.hibernate.sql.results.internal.SqlSelectionImpl) JdbcDelete(org.hibernate.sql.exec.spi.JdbcDelete) QuerySpec(org.hibernate.sql.ast.tree.select.QuerySpec) JdbcParameterBindings(org.hibernate.sql.exec.spi.JdbcParameterBindings)

Example 4 with ForeignKeyDescriptor

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

the class ManyToOneTest method basicTest.

@Test
public void basicTest(SessionFactoryScope scope) {
    final EntityPersister otherDescriptor = scope.getSessionFactory().getMappingMetamodel().findEntityDescriptor(OtherEntity.class);
    final ModelPart simpleEntityAssociation = otherDescriptor.findSubPart("simpleEntity");
    assertThat(simpleEntityAssociation, instanceOf(ToOneAttributeMapping.class));
    final ToOneAttributeMapping childAttributeMapping = (ToOneAttributeMapping) simpleEntityAssociation;
    ForeignKeyDescriptor foreignKeyDescriptor = childAttributeMapping.getForeignKeyDescriptor();
    foreignKeyDescriptor.visitKeySelectables((columnIndex, selection) -> {
        assertThat(selection.getContainingTableExpression(), is("other_entity"));
        assertThat(selection.getSelectionExpression(), is("simple_entity_id"));
    });
    foreignKeyDescriptor.visitTargetSelectables((columnIndex, selection) -> {
        assertThat(selection.getContainingTableExpression(), is("simple_entity"));
        assertThat(selection.getSelectionExpression(), is("id"));
    });
}
Also used : EntityPersister(org.hibernate.persister.entity.EntityPersister) ModelPart(org.hibernate.metamodel.mapping.ModelPart) ToOneAttributeMapping(org.hibernate.metamodel.mapping.internal.ToOneAttributeMapping) ForeignKeyDescriptor(org.hibernate.metamodel.mapping.ForeignKeyDescriptor) Test(org.junit.jupiter.api.Test)

Example 5 with ForeignKeyDescriptor

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

the class TemporaryTable method createIdTable.

public static TemporaryTable createIdTable(EntityMappingType entityDescriptor, Function<String, String> temporaryTableNameAdjuster, Dialect dialect, RuntimeModelCreationContext runtimeModelCreationContext) {
    return new TemporaryTable(entityDescriptor, temporaryTableNameAdjuster, dialect, temporaryTable -> {
        final List<TemporaryTableColumn> columns = new ArrayList<>();
        final PersistentClass entityBinding = runtimeModelCreationContext.getBootModel().getEntityBinding(entityDescriptor.getEntityName());
        final Iterator<JdbcMapping> jdbcMappings = entityDescriptor.getIdentifierMapping().getJdbcMappings().iterator();
        for (Column column : entityBinding.getKey().getColumns()) {
            final JdbcMapping jdbcMapping = jdbcMappings.next();
            columns.add(new TemporaryTableColumn(temporaryTable, column.getText(dialect), jdbcMapping, column.getSqlType(dialect, runtimeModelCreationContext.getMetadata()), column.isNullable(), true));
        }
        entityDescriptor.visitSubTypeAttributeMappings(attribute -> {
            if (attribute instanceof PluralAttributeMapping) {
                final PluralAttributeMapping pluralAttribute = (PluralAttributeMapping) attribute;
                if (pluralAttribute.getSeparateCollectionTable() != null) {
                    // Ensure that the FK target columns are available
                    ForeignKeyDescriptor keyDescriptor = pluralAttribute.getKeyDescriptor();
                    if (keyDescriptor == null) {
                        // and the callback is re-queued.
                        throw new IllegalStateException("Not yet ready: " + pluralAttribute);
                    }
                    final ModelPart fkTarget = keyDescriptor.getTargetPart();
                    if (!(fkTarget instanceof EntityIdentifierMapping)) {
                        final Value value = entityBinding.getSubclassProperty(pluralAttribute.getAttributeName()).getValue();
                        final Iterator<Selectable> columnIterator = ((Collection) value).getKey().getColumnIterator();
                        fkTarget.forEachSelectable((columnIndex, selection) -> {
                            final Selectable selectable = columnIterator.next();
                            if (selectable instanceof Column) {
                                final Column column = (Column) selectable;
                                columns.add(new TemporaryTableColumn(temporaryTable, selectable.getText(dialect), selection.getJdbcMapping(), column.getSqlType(dialect, runtimeModelCreationContext.getMetadata()), column.isNullable()));
                            }
                        });
                    }
                }
            }
        });
        return columns;
    });
}
Also used : JdbcMapping(org.hibernate.metamodel.mapping.JdbcMapping) ModelPart(org.hibernate.metamodel.mapping.ModelPart) ArrayList(java.util.ArrayList) PluralAttributeMapping(org.hibernate.metamodel.mapping.PluralAttributeMapping) Column(org.hibernate.mapping.Column) Selectable(org.hibernate.mapping.Selectable) ForeignKeyDescriptor(org.hibernate.metamodel.mapping.ForeignKeyDescriptor) EntityIdentifierMapping(org.hibernate.metamodel.mapping.EntityIdentifierMapping) SimpleValue(org.hibernate.mapping.SimpleValue) Value(org.hibernate.mapping.Value) PersistentClass(org.hibernate.mapping.PersistentClass)

Aggregations

ForeignKeyDescriptor (org.hibernate.metamodel.mapping.ForeignKeyDescriptor)21 ModelPart (org.hibernate.metamodel.mapping.ModelPart)12 ToOneAttributeMapping (org.hibernate.metamodel.mapping.internal.ToOneAttributeMapping)10 EntityPersister (org.hibernate.persister.entity.EntityPersister)9 EntityIdentifierMapping (org.hibernate.metamodel.mapping.EntityIdentifierMapping)7 NavigablePath (org.hibernate.query.spi.NavigablePath)7 QuerySpec (org.hibernate.sql.ast.tree.select.QuerySpec)7 AttributeMapping (org.hibernate.metamodel.mapping.AttributeMapping)6 PluralAttributeMapping (org.hibernate.metamodel.mapping.PluralAttributeMapping)5 Expression (org.hibernate.sql.ast.tree.expression.Expression)5 TableGroup (org.hibernate.sql.ast.tree.from.TableGroup)5 SqlSelectionImpl (org.hibernate.sql.results.internal.SqlSelectionImpl)5 SessionFactoryImplementor (org.hibernate.engine.spi.SessionFactoryImplementor)4 BasicValuedModelPart (org.hibernate.metamodel.mapping.BasicValuedModelPart)4 SqlExpressionResolver (org.hibernate.sql.ast.spi.SqlExpressionResolver)4 ColumnReference (org.hibernate.sql.ast.tree.expression.ColumnReference)4 Test (org.junit.jupiter.api.Test)4 AbstractMap (java.util.AbstractMap)3 ArrayList (java.util.ArrayList)3 List (java.util.List)3