Search in sources :

Example 26 with PluralAttributeMapping

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

the class YearMappingTests method basicAssertions.

@Test
public void basicAssertions(SessionFactoryScope scope) {
    final SessionFactoryImplementor sessionFactory = scope.getSessionFactory();
    final EntityPersister entityDescriptor = sessionFactory.getMappingMetamodel().getEntityDescriptor(YearMappingTestEntity.class);
    {
        final BasicAttributeMapping yearAttribute = (BasicAttributeMapping) entityDescriptor.findAttributeMapping("year");
        assertThat(yearAttribute.getJdbcMapping().getJdbcType().getJdbcTypeCode()).isEqualTo(Types.INTEGER);
        assertThat(yearAttribute.getJdbcMapping().getJavaTypeDescriptor().getJavaTypeClass()).isEqualTo(Year.class);
    }
    {
        final PluralAttributeMapping yearsAttribute = (PluralAttributeMapping) entityDescriptor.findAttributeMapping("years");
        final BasicValuedCollectionPart elementDescriptor = (BasicValuedCollectionPart) yearsAttribute.getElementDescriptor();
        assertThat(elementDescriptor.getJdbcMapping().getJdbcType().getJdbcTypeCode()).isEqualTo(Types.INTEGER);
        assertThat(elementDescriptor.getJdbcMapping().getJavaTypeDescriptor().getJavaTypeClass()).isEqualTo(Year.class);
    }
    {
        final PluralAttributeMapping countByYearAttribute = (PluralAttributeMapping) entityDescriptor.findAttributeMapping("countByYear");
        final BasicValuedCollectionPart keyDescriptor = (BasicValuedCollectionPart) countByYearAttribute.getIndexDescriptor();
        assertThat(keyDescriptor.getJdbcMapping().getJdbcType().getJdbcTypeCode()).isEqualTo(Types.INTEGER);
        assertThat(keyDescriptor.getJdbcMapping().getJavaTypeDescriptor().getJavaTypeClass()).isEqualTo(Year.class);
    }
}
Also used : EntityPersister(org.hibernate.persister.entity.EntityPersister) Year(java.time.Year) SessionFactoryImplementor(org.hibernate.engine.spi.SessionFactoryImplementor) BasicAttributeMapping(org.hibernate.metamodel.mapping.internal.BasicAttributeMapping) PluralAttributeMapping(org.hibernate.metamodel.mapping.PluralAttributeMapping) BasicValuedCollectionPart(org.hibernate.metamodel.mapping.internal.BasicValuedCollectionPart) Test(org.junit.jupiter.api.Test)

Example 27 with PluralAttributeMapping

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

the class TemporaryTable method createEntityTable.

public static TemporaryTable createEntityTable(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 IdentifierGenerator identifierGenerator = entityDescriptor.getEntityPersister().getIdentifierGenerator();
        final boolean identityColumn = identifierGenerator instanceof PostInsertIdentifierGenerator;
        final boolean hasOptimizer;
        if (identityColumn) {
            hasOptimizer = false;
            final Iterator<JdbcMapping> jdbcMappings = entityDescriptor.getIdentifierMapping().getJdbcMappings().iterator();
            for (Column column : entityBinding.getKey().getColumns()) {
                final JdbcMapping jdbcMapping = jdbcMappings.next();
                columns.add(new TemporaryTableColumn(temporaryTable, ENTITY_TABLE_IDENTITY_COLUMN, jdbcMapping, column.getSqlType(dialect, runtimeModelCreationContext.getMetadata()) + " " + dialect.getIdentityColumnSupport().getIdentityColumnString(column.getSqlTypeCode(runtimeModelCreationContext.getMetadata())), // column.isNullable()
                true, true));
            }
        } else {
            if (identifierGenerator instanceof OptimizableGenerator) {
                final Optimizer optimizer = ((OptimizableGenerator) identifierGenerator).getOptimizer();
                hasOptimizer = optimizer != null && optimizer.getIncrementSize() > 1;
            } else {
                hasOptimizer = false;
            }
        }
        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()), // We have to set the identity column after the root table insert
            column.isNullable() || identityColumn || hasOptimizer, !identityColumn && !hasOptimizer));
        }
        final EntityDiscriminatorMapping discriminatorMapping = entityDescriptor.getDiscriminatorMapping();
        if (entityBinding.getDiscriminator() != null && !discriminatorMapping.isFormula()) {
            final Column discriminator = entityBinding.getDiscriminator().getColumns().get(0);
            columns.add(new TemporaryTableColumn(temporaryTable, discriminator.getText(dialect), discriminatorMapping.getJdbcMapping(), discriminator.getSqlType(dialect, runtimeModelCreationContext.getMetadata()), // We have to set the identity column after the root table insert
            discriminator.isNullable()));
        }
        // Collect all columns for all entity subtype attributes
        entityDescriptor.visitSubTypeAttributeMappings(attribute -> {
            if (!(attribute instanceof PluralAttributeMapping)) {
                final SimpleValue value = (SimpleValue) entityBinding.getSubclassProperty(attribute.getAttributeName()).getValue();
                final Iterator<Selectable> columnIterator = value.getConstraintColumnIterator();
                attribute.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()), // Treat regular temporary table columns as nullable for simplicity
                        true));
                    }
                });
            }
        });
        if (hasOptimizer) {
            // We add a special row number column that we can use to identify and join rows
            final BasicType<Integer> integerBasicType = entityDescriptor.getEntityPersister().getFactory().getTypeConfiguration().getBasicTypeForJavaType(Integer.class);
            final String rowNumberType;
            if (dialect.supportsWindowFunctions()) {
                rowNumberType = dialect.getTypeName(integerBasicType.getJdbcType().getJdbcTypeCode(), dialect.getSizeStrategy().resolveSize(integerBasicType.getJdbcType(), integerBasicType.getJavaTypeDescriptor(), null, null, null));
            } else if (dialect.getIdentityColumnSupport().supportsIdentityColumns()) {
                rowNumberType = dialect.getTypeName(integerBasicType.getJdbcType().getJdbcTypeCode(), dialect.getSizeStrategy().resolveSize(integerBasicType.getJdbcType(), integerBasicType.getJavaTypeDescriptor(), null, null, null)) + " " + dialect.getIdentityColumnSupport().getIdentityColumnString(integerBasicType.getJdbcType().getJdbcTypeCode());
            } else {
                LOG.multiTableInsertNotAvailable(entityBinding.getEntityName());
                rowNumberType = dialect.getTypeName(integerBasicType.getJdbcType().getJdbcTypeCode(), dialect.getSizeStrategy().resolveSize(integerBasicType.getJdbcType(), integerBasicType.getJavaTypeDescriptor(), null, null, null));
            }
            columns.add(new TemporaryTableColumn(temporaryTable, "rn_", integerBasicType, rowNumberType, false, true));
        }
        return columns;
    });
}
Also used : JdbcMapping(org.hibernate.metamodel.mapping.JdbcMapping) OptimizableGenerator(org.hibernate.id.OptimizableGenerator) Optimizer(org.hibernate.id.enhanced.Optimizer) ArrayList(java.util.ArrayList) PluralAttributeMapping(org.hibernate.metamodel.mapping.PluralAttributeMapping) EntityDiscriminatorMapping(org.hibernate.metamodel.mapping.EntityDiscriminatorMapping) SimpleValue(org.hibernate.mapping.SimpleValue) PostInsertIdentifierGenerator(org.hibernate.id.PostInsertIdentifierGenerator) Column(org.hibernate.mapping.Column) Selectable(org.hibernate.mapping.Selectable) PersistentClass(org.hibernate.mapping.PersistentClass) PostInsertIdentifierGenerator(org.hibernate.id.PostInsertIdentifierGenerator) IdentifierGenerator(org.hibernate.id.IdentifierGenerator)

Example 28 with PluralAttributeMapping

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

the class SqmUtil method createValueBindings.

private static void createValueBindings(JdbcParameterBindings jdbcParameterBindings, QueryParameterImplementor<?> domainParam, QueryParameterBinding<?> domainParamBinding, Bindable parameterType, List<JdbcParameter> jdbcParams, Object bindValue, Function<NavigablePath, TableGroup> tableGroupLocator, SharedSessionContractImplementor session) {
    if (parameterType == null) {
        throw new SqlTreeCreationException("Unable to interpret mapping-model type for Query parameter : " + domainParam);
    }
    if (parameterType instanceof EntityIdentifierMapping) {
        final EntityIdentifierMapping identifierMapping = (EntityIdentifierMapping) parameterType;
        final EntityMappingType entityMapping = identifierMapping.findContainingEntityMapping();
        if (entityMapping.getRepresentationStrategy().getInstantiator().isInstance(bindValue, session.getFactory())) {
            bindValue = identifierMapping.getIdentifier(bindValue);
        }
    } else if (parameterType instanceof EntityMappingType) {
        final EntityIdentifierMapping identifierMapping = ((EntityMappingType) parameterType).getIdentifierMapping();
        final EntityMappingType entityMapping = identifierMapping.findContainingEntityMapping();
        parameterType = identifierMapping;
        if (entityMapping.getRepresentationStrategy().getInstantiator().isInstance(bindValue, session.getFactory())) {
            bindValue = identifierMapping.getIdentifier(bindValue);
        }
    } else if (parameterType instanceof EntityAssociationMapping) {
        EntityAssociationMapping association = (EntityAssociationMapping) parameterType;
        bindValue = association.getForeignKeyDescriptor().getAssociationKeyFromSide(bindValue, association.getSideNature().inverse(), session);
        parameterType = association.getForeignKeyDescriptor();
    } else if (parameterType instanceof PluralAttributeMapping) {
        // for now, let's blow up and see where this happens and fix the specifics...
        throw new NotYetImplementedFor6Exception("Binding parameters whose inferred type comes from plural attribute not yet implemented");
    }
    int offset = jdbcParameterBindings.registerParametersForEachJdbcValue(bindValue, Clause.IRRELEVANT, parameterType, jdbcParams, session);
    assert offset == jdbcParams.size();
}
Also used : EntityAssociationMapping(org.hibernate.metamodel.mapping.EntityAssociationMapping) SqlTreeCreationException(org.hibernate.sql.ast.SqlTreeCreationException) EntityIdentifierMapping(org.hibernate.metamodel.mapping.EntityIdentifierMapping) PluralAttributeMapping(org.hibernate.metamodel.mapping.PluralAttributeMapping) NotYetImplementedFor6Exception(org.hibernate.NotYetImplementedFor6Exception) EntityMappingType(org.hibernate.metamodel.mapping.EntityMappingType)

Example 29 with PluralAttributeMapping

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

the class InlineDeleteHandler method execute.

@Override
public int execute(DomainQueryExecutionContext executionContext) {
    final List<Object> idsAndFks = MatchingIdSelectionHelper.selectMatchingIds(sqmDeleteStatement, domainParameterXref, executionContext);
    if (idsAndFks == null || idsAndFks.isEmpty()) {
        return 0;
    }
    final SessionFactoryImplementor factory = executionContext.getSession().getFactory();
    final String mutatingEntityName = sqmDeleteStatement.getTarget().getModel().getHibernateEntityName();
    final EntityMappingType entityDescriptor = factory.getRuntimeMetamodels().getEntityMappingType(mutatingEntityName);
    final JdbcParameterBindings jdbcParameterBindings = new JdbcParameterBindingsImpl(domainParameterXref.getQueryParameterCount());
    // delete from the tables
    final MutableInteger valueIndexCounter = new MutableInteger();
    entityDescriptor.visitSubTypeAttributeMappings(attribute -> {
        if (attribute instanceof PluralAttributeMapping) {
            final PluralAttributeMapping pluralAttribute = (PluralAttributeMapping) attribute;
            if (pluralAttribute.getSeparateCollectionTable() != null) {
                // this collection has a separate collection table, meaning it is one of:
                // 1) element-collection
                // 2) many-to-many
                // 3) one-to many using a dedicated join-table
                // 
                // in all of these cases, we should clean up the matching rows in the
                // collection table
                final ModelPart fkTargetPart = pluralAttribute.getKeyDescriptor().getTargetPart();
                final int valueIndex;
                if (fkTargetPart instanceof EntityIdentifierMapping) {
                    valueIndex = 0;
                } else {
                    if (valueIndexCounter.get() == 0) {
                        valueIndexCounter.set(entityDescriptor.getIdentifierMapping().getJdbcTypeCount());
                    }
                    valueIndex = valueIndexCounter.get();
                    valueIndexCounter.plus(fkTargetPart.getJdbcTypeCount());
                }
                executeDelete(pluralAttribute.getSeparateCollectionTable(), entityDescriptor, () -> fkTargetPart::forEachSelectable, idsAndFks, valueIndex, fkTargetPart, jdbcParameterBindings, executionContext);
            }
        }
    });
    entityDescriptor.visitConstraintOrderedTables((tableExpression, tableKeyColumnsVisitationSupplier) -> {
        executeDelete(tableExpression, entityDescriptor, tableKeyColumnsVisitationSupplier, idsAndFks, 0, null, jdbcParameterBindings, executionContext);
    });
    return idsAndFks.size();
}
Also used : JdbcParameterBindingsImpl(org.hibernate.sql.exec.internal.JdbcParameterBindingsImpl) ModelPart(org.hibernate.metamodel.mapping.ModelPart) SessionFactoryImplementor(org.hibernate.engine.spi.SessionFactoryImplementor) MutableInteger(org.hibernate.internal.util.MutableInteger) PluralAttributeMapping(org.hibernate.metamodel.mapping.PluralAttributeMapping) EntityIdentifierMapping(org.hibernate.metamodel.mapping.EntityIdentifierMapping) EntityMappingType(org.hibernate.metamodel.mapping.EntityMappingType) JdbcParameterBindings(org.hibernate.sql.exec.spi.JdbcParameterBindings)

Example 30 with PluralAttributeMapping

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

the class ElementCollectionSortingTest method checkSQLOrderBy.

private void checkSQLOrderBy(Session session, String entityName, String propertyName, SortOrder order) {
    String roleName = entityName + "." + propertyName;
    String alias = "alias1";
    BasicCollectionPersister collectionPersister = (BasicCollectionPersister) session.getSessionFactory().getCollectionMetadata(roleName);
    assertTrue(collectionPersister.hasOrdering());
    PluralAttributeMapping attributeMapping = collectionPersister.getAttributeMapping();
    assertThat(attributeMapping.getFetchableName(), is(propertyName));
    OrderByFragmentImpl orderByFragment = (OrderByFragmentImpl) attributeMapping.getOrderByFragment();
    List<OrderingSpecification> fragmentSpecs = orderByFragment.getFragmentSpecs();
    assertThat(fragmentSpecs.size(), is(1));
    assertThat(fragmentSpecs.get(0).getSortOrder(), is(order));
}
Also used : BasicCollectionPersister(org.hibernate.persister.collection.BasicCollectionPersister) PluralAttributeMapping(org.hibernate.metamodel.mapping.PluralAttributeMapping) OrderingSpecification(org.hibernate.metamodel.mapping.ordering.ast.OrderingSpecification) OrderByFragmentImpl(org.hibernate.metamodel.mapping.ordering.OrderByFragmentImpl)

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