use of org.hibernate.metamodel.mapping.Association in project hibernate-orm by hibernate.
the class AbstractEntityPersister method selectFragment.
@Override
public String selectFragment(String alias, String suffix) {
final QuerySpec rootQuerySpec = new QuerySpec(true);
final String rootTableName = getRootTableName();
final LoaderSqlAstCreationState sqlAstCreationState = new LoaderSqlAstCreationState(rootQuerySpec, new SqlAliasBaseManager(), new SimpleFromClauseAccessImpl(), LockOptions.NONE, (fetchParent, querySpec, creationState) -> {
final List<Fetch> fetches = new ArrayList<>();
fetchParent.getReferencedMappingContainer().visitFetchables(fetchable -> {
// Ignore plural attributes
if (fetchable instanceof PluralAttributeMapping) {
return;
}
FetchTiming fetchTiming = fetchable.getMappedFetchOptions().getTiming();
final boolean selectable;
if (fetchable instanceof StateArrayContributorMapping) {
final int propertyNumber = ((StateArrayContributorMapping) fetchable).getStateArrayPosition();
final int tableNumber = getSubclassPropertyTableNumber(propertyNumber);
selectable = !isSubclassTableSequentialSelect(tableNumber) && propertySelectable[propertyNumber];
} else {
selectable = true;
}
if (fetchable instanceof BasicValuedModelPart) {
// Ignore lazy basic columns
if (fetchTiming == FetchTiming.DELAYED) {
return;
}
} else if (fetchable instanceof Association) {
final Association association = (Association) fetchable;
// Ignore the fetchable if the FK is on the other side
if (association.getSideNature() == ForeignKeyDescriptor.Nature.TARGET) {
return;
}
// Ensure the FK comes from the root table
if (!rootTableName.equals(association.getForeignKeyDescriptor().getKeyTable())) {
return;
}
fetchTiming = FetchTiming.DELAYED;
}
if (selectable) {
final NavigablePath navigablePath = fetchParent.resolveNavigablePath(fetchable);
final Fetch fetch = fetchParent.generateFetchableFetch(fetchable, navigablePath, fetchTiming, true, null, creationState);
fetches.add(fetch);
}
}, null);
return fetches;
}, true, getFactory());
final NavigablePath entityPath = new NavigablePath(getRootPathName());
final TableGroup rootTableGroup = createRootTableGroup(true, entityPath, null, () -> p -> {
}, new SqlAliasBaseConstant(alias), sqlAstCreationState.getSqlExpressionResolver(), sqlAstCreationState.getFromClauseAccess(), getFactory());
rootQuerySpec.getFromClause().addRoot(rootTableGroup);
sqlAstCreationState.getFromClauseAccess().registerTableGroup(entityPath, rootTableGroup);
createDomainResult(entityPath, rootTableGroup, null, sqlAstCreationState);
// Wrap expressions with aliases
final SelectClause selectClause = rootQuerySpec.getSelectClause();
final List<SqlSelection> sqlSelections = selectClause.getSqlSelections();
int i = 0;
for (String identifierAlias : identifierAliases) {
sqlSelections.set(i, new SqlSelectionImpl(i, i + 1, new AliasedExpression(sqlSelections.get(i).getExpression(), identifierAlias + suffix)));
i++;
}
if (entityMetamodel.hasSubclasses()) {
sqlSelections.set(i, new SqlSelectionImpl(i, i + 1, new AliasedExpression(sqlSelections.get(i).getExpression(), getDiscriminatorAlias() + suffix)));
i++;
}
if (hasRowId()) {
sqlSelections.set(i, new SqlSelectionImpl(i, i + 1, new AliasedExpression(sqlSelections.get(i).getExpression(), ROWID_ALIAS + suffix)));
i++;
}
final String[] columnAliases = getSubclassColumnAliasClosure();
final String[] formulaAliases = getSubclassFormulaAliasClosure();
int columnIndex = 0;
int formulaIndex = 0;
for (; i < sqlSelections.size(); i++) {
final SqlSelection sqlSelection = sqlSelections.get(i);
final ColumnReference columnReference = (ColumnReference) sqlSelection.getExpression();
final String selectAlias;
if (!columnReference.isColumnExpressionFormula()) {
// Skip over columns that are not selectable like in the fetch generation
while (!subclassColumnSelectableClosure[columnIndex]) {
columnIndex++;
}
selectAlias = columnAliases[columnIndex++] + suffix;
} else {
selectAlias = formulaAliases[formulaIndex++] + suffix;
}
sqlSelections.set(i, new SqlSelectionImpl(sqlSelection.getValuesArrayPosition(), sqlSelection.getJdbcResultSetIndex(), new AliasedExpression(sqlSelection.getExpression(), selectAlias)));
}
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;
}
use of org.hibernate.metamodel.mapping.Association in project hibernate-orm by hibernate.
the class DomainResultCreationStateImpl method visitFetches.
@Override
public List<Fetch> visitFetches(FetchParent fetchParent) {
final FetchableContainer fetchableContainer = fetchParent.getReferencedMappingContainer();
final List<Fetch> fetches = CollectionHelper.arrayList(fetchableContainer.getNumberOfFetchables());
final Consumer<Fetchable> fetchableConsumer = fetchable -> {
final String fetchableName = fetchable.getFetchableName();
Map.Entry<String, NavigablePath> currentEntry;
if (relativePathStack.isEmpty()) {
currentEntry = new AbstractMap.SimpleEntry<>(getRelativePath("", fetchable, fetchableContainer), new NavigablePath(fetchableName));
} else {
final Map.Entry<String, NavigablePath> oldEntry = relativePathStack.getCurrent();
final String key = oldEntry.getKey();
currentEntry = new AbstractMap.SimpleEntry<>(getRelativePath(key, fetchable, fetchableContainer), oldEntry.getValue().append(fetchableName));
}
// todo (6.0): figure out if we can somehow create the navigable paths in a better way
final String fullPath = currentEntry.getKey();
FetchBuilder explicitFetchBuilder = fetchBuilderResolverStack.getCurrent().apply(fullPath);
DynamicFetchBuilderLegacy fetchBuilderLegacy;
if (explicitFetchBuilder == null) {
fetchBuilderLegacy = legacyFetchResolver.resolve(fromClauseAccess.findTableGroup(fetchParent.getNavigablePath()).getPrimaryTableReference().getIdentificationVariable(), fetchableName);
} else {
fetchBuilderLegacy = null;
}
if (fetchable instanceof Association && fetchable.getMappedFetchOptions().getTiming() == FetchTiming.DELAYED) {
final Association association = (Association) fetchable;
final ForeignKeyDescriptor foreignKeyDescriptor = association.getForeignKeyDescriptor();
final String partName = attributeName(foreignKeyDescriptor.getSide(association.getSideNature().inverse()).getModelPart());
// If there are no fetch builders for this association, we only want to fetch the FK
if (explicitFetchBuilder == null && fetchBuilderLegacy == null && partName != null) {
currentEntry = new AbstractMap.SimpleEntry<>(currentEntry.getKey() + "." + partName, currentEntry.getValue().append(partName));
explicitFetchBuilder = fetchBuilderResolverStack.getCurrent().apply(currentEntry.getKey());
if (explicitFetchBuilder == null) {
fetchBuilderLegacy = legacyFetchResolver.resolve(fromClauseAccess.findTableGroup(fetchParent.getNavigablePath()).getPrimaryTableReference().getIdentificationVariable(), fetchableName);
}
}
}
relativePathStack.push(currentEntry);
try {
final NavigablePath fetchPath = fetchParent.resolveNavigablePath(fetchable);
final FetchBuilder fetchBuilder;
if (explicitFetchBuilder != null) {
fetchBuilder = explicitFetchBuilder;
} else {
if (fetchBuilderLegacy == null) {
fetchBuilder = Builders.implicitFetchBuilder(fetchPath, fetchable, this);
} else {
fetchBuilder = fetchBuilderLegacy;
}
}
final Fetch fetch = fetchBuilder.buildFetch(fetchParent, fetchPath, jdbcResultsMetadata, (s, s2) -> {
throw new UnsupportedOperationException();
}, this);
fetches.add(fetch);
} finally {
relativePathStack.pop();
}
};
boolean previous = this.processingKeyFetches;
this.processingKeyFetches = true;
if (fetchableContainer instanceof EntityValuedModelPart) {
final EntityValuedModelPart entityValuedFetchable = (EntityValuedModelPart) fetchableContainer;
final EntityIdentifierMapping identifierMapping = entityValuedFetchable.getEntityMappingType().getIdentifierMapping();
final boolean idClass = identifierMapping instanceof NonAggregatedIdentifierMapping;
final String identifierAttributeName = attributeName(identifierMapping);
if (idClass) {
final Map.Entry<String, NavigablePath> oldEntry = relativePathStack.getCurrent();
relativePathStack.push(new AbstractMap.SimpleEntry<>(oldEntry == null ? "" : oldEntry.getKey(), new EntityIdentifierNavigablePath(oldEntry == null ? fetchParent.getNavigablePath() : oldEntry.getValue(), identifierAttributeName)));
} else if (identifierMapping instanceof CompositeIdentifierMapping) {
final Map.Entry<String, NavigablePath> oldEntry = relativePathStack.getCurrent();
relativePathStack.push(new AbstractMap.SimpleEntry<>(oldEntry == null ? identifierAttributeName : oldEntry.getKey() + "." + identifierAttributeName, new EntityIdentifierNavigablePath(oldEntry == null ? fetchParent.getNavigablePath() : oldEntry.getValue(), identifierAttributeName)));
}
try {
if (identifierMapping instanceof FetchableContainer) {
// essentially means the entity has a composite id - ask the embeddable to visit its fetchables
((FetchableContainer) identifierMapping).visitFetchables(fetchableConsumer, null);
} else {
fetchableConsumer.accept((Fetchable) identifierMapping);
}
} finally {
this.processingKeyFetches = previous;
if (idClass) {
this.relativePathStack.pop();
}
}
}
fetchableContainer.visitKeyFetchables(fetchableConsumer, null);
fetchableContainer.visitFetchables(fetchableConsumer, null);
return fetches;
}
use of org.hibernate.metamodel.mapping.Association in project hibernate-orm by hibernate.
the class BaseSqmToSqlAstConverter method visitLiteral.
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// General expressions
@Override
public Expression visitLiteral(SqmLiteral<?> literal) {
if (literal instanceof SqmLiteralNull) {
MappingModelExpressible<?> mappingModelExpressible = resolveInferredType();
if (mappingModelExpressible == null) {
mappingModelExpressible = determineCurrentExpressible(literal);
}
if (mappingModelExpressible instanceof BasicValuedMapping) {
return new QueryLiteral<>(null, (BasicValuedMapping) mappingModelExpressible);
}
final MappingModelExpressible<?> keyExpressible = getKeyExpressible(mappingModelExpressible);
if (keyExpressible == null) {
// Default to the Object type
return new QueryLiteral<>(null, basicType(Object.class));
}
final List<Expression> expressions = new ArrayList<>(keyExpressible.getJdbcTypeCount());
keyExpressible.forEachJdbcType((index, jdbcMapping) -> expressions.add(new QueryLiteral<>(null, (BasicValuedMapping) jdbcMapping)));
return new SqlTuple(expressions, mappingModelExpressible);
}
final MappingModelExpressible<?> inferableExpressible = resolveInferredType();
if (inferableExpressible instanceof ConvertibleModelPart) {
final ConvertibleModelPart convertibleModelPart = (ConvertibleModelPart) inferableExpressible;
if (convertibleModelPart.getValueConverter() != null) {
return new QueryLiteral<>(literal.getLiteralValue(), convertibleModelPart);
}
} else // Special case for when we create an entity literal through the JPA CriteriaBuilder.literal API
if (inferableExpressible instanceof EntityDiscriminatorMapping) {
final EntityDiscriminatorMapping discriminatorMapping = (EntityDiscriminatorMapping) inferableExpressible;
final Object literalValue = literal.getLiteralValue();
final EntityPersister mappingDescriptor;
if (literalValue instanceof Class<?>) {
mappingDescriptor = creationContext.getSessionFactory().getRuntimeMetamodels().getMappingMetamodel().getEntityDescriptor((Class<?>) literalValue);
} else {
final JavaType<?> javaType = discriminatorMapping.getJdbcMapping().getJavaTypeDescriptor();
final Object discriminatorValue;
if (javaType.getJavaTypeClass().isInstance(literalValue)) {
discriminatorValue = literalValue;
} else if (literalValue instanceof CharSequence) {
discriminatorValue = javaType.fromString((CharSequence) literalValue);
} else if (creationContext.getSessionFactory().getJpaMetamodel().getJpaCompliance().isLoadByIdComplianceEnabled()) {
discriminatorValue = literalValue;
} else {
discriminatorValue = javaType.coerce(literalValue, null);
}
final String entityName = discriminatorMapping.getConcreteEntityNameForDiscriminatorValue(discriminatorValue);
mappingDescriptor = creationContext.getSessionFactory().getRuntimeMetamodels().getMappingMetamodel().getEntityDescriptor(entityName);
}
return new EntityTypeLiteral(mappingDescriptor);
}
final MappingModelExpressible<?> expressible;
final MappingModelExpressible<?> localExpressible = SqmMappingModelHelper.resolveMappingModelExpressible(literal, creationContext.getSessionFactory().getRuntimeMetamodels().getMappingMetamodel(), getFromClauseAccess()::findTableGroup);
if (localExpressible == null) {
expressible = getElementExpressible(inferableExpressible);
} else {
final MappingModelExpressible<?> elementExpressible = getElementExpressible(localExpressible);
if (elementExpressible instanceof BasicType) {
expressible = InferredBasicValueResolver.resolveSqlTypeIndicators(this, (BasicType) elementExpressible, literal.getJavaTypeDescriptor());
} else {
expressible = elementExpressible;
}
}
if (expressible instanceof EntityIdentifierMapping && literal.getNodeType() instanceof EntityTypeImpl) {
return new QueryLiteral<>(((EntityIdentifierMapping) expressible).getIdentifier(literal.getLiteralValue()), (BasicValuedMapping) expressible);
}
if (expressible instanceof BasicValuedMapping) {
return new QueryLiteral<>(literal.getLiteralValue(), (BasicValuedMapping) expressible);
}
// Handling other values might seem unnecessary, but with JPA Criteria it is totally possible to have such literals
if (expressible instanceof EmbeddableValuedModelPart) {
final EmbeddableValuedModelPart embeddableValuedModelPart = (EmbeddableValuedModelPart) expressible;
final List<Expression> list = new ArrayList<>(embeddableValuedModelPart.getJdbcTypeCount());
embeddableValuedModelPart.forEachJdbcValue(literal.getLiteralValue(), null, (selectionIndex, value, jdbcMapping) -> list.add(new QueryLiteral<>(value, (BasicValuedMapping) jdbcMapping)), null);
return new SqlTuple(list, expressible);
} else if (expressible instanceof EntityValuedModelPart) {
final EntityValuedModelPart entityValuedModelPart = (EntityValuedModelPart) expressible;
final Object associationKey;
final ModelPart associationKeyPart;
if (entityValuedModelPart instanceof Association) {
final Association association = (Association) entityValuedModelPart;
final ForeignKeyDescriptor foreignKeyDescriptor = association.getForeignKeyDescriptor();
associationKey = foreignKeyDescriptor.getAssociationKeyFromSide(literal.getLiteralValue(), association.getSideNature().inverse(), null);
associationKeyPart = foreignKeyDescriptor.getPart(association.getSideNature());
} else {
final EntityIdentifierMapping identifierMapping = entityValuedModelPart.getEntityMappingType().getIdentifierMapping();
associationKeyPart = identifierMapping;
associationKey = identifierMapping.getIdentifier(literal.getLiteralValue(), null);
}
if (associationKeyPart instanceof BasicValuedMapping) {
return new QueryLiteral<>(associationKey, (BasicValuedMapping) associationKeyPart);
} else {
final List<Expression> list = new ArrayList<>(associationKeyPart.getJdbcTypeCount());
associationKeyPart.forEachJdbcValue(associationKey, null, (selectionIndex, value, jdbcMapping) -> list.add(new QueryLiteral<>(value, (BasicValuedMapping) jdbcMapping)), null);
return new SqlTuple(list, associationKeyPart);
}
} else {
return new QueryLiteral<>(literal.getLiteralValue(), creationContext.getSessionFactory().getTypeConfiguration().getBasicTypeRegistry().getRegisteredType(((BasicSqmPathSource<?>) literal.getNodeType()).getSqmPathType().getJavaType().getName()));
}
}
use of org.hibernate.metamodel.mapping.Association in project hibernate-orm by hibernate.
the class BaseSqmToSqlAstConverter method createCteTable.
public static CteTable createCteTable(SqmCteTable sqmCteTable, List<SqmCteTableColumn> sqmCteColumns, SessionFactoryImplementor factory) {
final List<CteColumn> sqlCteColumns = new ArrayList<>(sqmCteColumns.size());
for (int i = 0; i < sqmCteColumns.size(); i++) {
final SqmCteTableColumn sqmCteTableColumn = sqmCteColumns.get(i);
ValueMapping valueMapping = sqmCteTableColumn.getType();
if (valueMapping instanceof Association) {
valueMapping = ((Association) valueMapping).getForeignKeyDescriptor();
}
if (valueMapping instanceof EmbeddableValuedModelPart) {
valueMapping.forEachJdbcType((index, jdbcMapping) -> sqlCteColumns.add(new CteColumn(sqmCteTableColumn.getColumnName() + "_" + index, jdbcMapping)));
} else {
sqlCteColumns.add(new CteColumn(sqmCteTableColumn.getColumnName(), ((BasicValuedMapping) valueMapping).getJdbcMapping()));
}
}
return new CteTable(sqmCteTable.getCteName(), sqlCteColumns, factory);
}
Aggregations