Search in sources :

Example 26 with EntityMappingType

use of org.hibernate.metamodel.mapping.EntityMappingType 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)

Example 27 with EntityMappingType

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

the class AbstractReadWriteTests method test.

@Test
public void test(SessionFactoryScope scope) {
    final EntityMappingType entityMapping = scope.getSessionFactory().getRuntimeMetamodels().getEntityMappingType(ReadWriteEntity.class);
    final BasicAttributeMapping attribute = (BasicAttributeMapping) entityMapping.findAttributeMapping("value");
    attribute.forEachSelectable((i, selectable) -> {
        final String readExpression = selectable.getCustomReadExpression();
    });
    scope.inTransaction((session) -> {
        session.createQuery("from ReadWriteEntity").list();
    });
}
Also used : BasicAttributeMapping(org.hibernate.metamodel.mapping.internal.BasicAttributeMapping) EntityMappingType(org.hibernate.metamodel.mapping.EntityMappingType) Test(org.junit.jupiter.api.Test)

Example 28 with EntityMappingType

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

the class NaturalIdResolutionsImpl method manageSharedResolution.

private void manageSharedResolution(EntityPersister persister, final Object id, Object naturalIdValues, Object previousNaturalIdValues, CachedNaturalIdValueSource source) {
    final NaturalIdDataAccess cacheAccess = persister.getNaturalIdMapping().getCacheAccess();
    if (cacheAccess == null) {
        return;
    }
    final EntityMappingType rootEntityDescriptor = persister.getRootEntityDescriptor();
    final EntityPersister rootEntityPersister = rootEntityDescriptor.getEntityPersister();
    final Object cacheKey = cacheAccess.generateCacheKey(naturalIdValues, rootEntityPersister, session());
    final SessionFactoryImplementor factory = session().getFactory();
    final StatisticsImplementor statistics = factory.getStatistics();
    switch(source) {
        case LOAD:
            {
                if (CacheHelper.fromSharedCache(session(), cacheKey, cacheAccess) != null) {
                    // prevent identical re-cachings
                    return;
                }
                final boolean put = cacheAccess.putFromLoad(session(), cacheKey, id, null);
                if (put && statistics.isStatisticsEnabled()) {
                    statistics.naturalIdCachePut(rootEntityDescriptor.getNavigableRole(), cacheAccess.getRegion().getName());
                }
                break;
            }
        case INSERT:
            {
                final boolean put = cacheAccess.insert(session(), cacheKey, id);
                if (put && statistics.isStatisticsEnabled()) {
                    statistics.naturalIdCachePut(rootEntityDescriptor.getNavigableRole(), cacheAccess.getRegion().getName());
                }
                ((EventSource) session()).getActionQueue().registerProcess((success, session) -> {
                    if (success) {
                        final boolean put1 = cacheAccess.afterInsert(session, cacheKey, id);
                        if (put1 && statistics.isStatisticsEnabled()) {
                            statistics.naturalIdCachePut(rootEntityDescriptor.getNavigableRole(), cacheAccess.getRegion().getName());
                        }
                    } else {
                        cacheAccess.evict(cacheKey);
                    }
                });
                break;
            }
        case UPDATE:
            {
                final Object previousCacheKey = cacheAccess.generateCacheKey(previousNaturalIdValues, rootEntityPersister, session());
                if (cacheKey.equals(previousCacheKey)) {
                    // prevent identical re-caching, solves HHH-7309
                    return;
                }
                final SoftLock removalLock = cacheAccess.lockItem(session(), previousCacheKey, null);
                cacheAccess.remove(session(), previousCacheKey);
                final SoftLock lock = cacheAccess.lockItem(session(), cacheKey, null);
                final boolean put = cacheAccess.update(session(), cacheKey, id);
                if (put && statistics.isStatisticsEnabled()) {
                    statistics.naturalIdCachePut(rootEntityDescriptor.getNavigableRole(), cacheAccess.getRegion().getName());
                }
                ((EventSource) session()).getActionQueue().registerProcess((success, session) -> {
                    cacheAccess.unlockItem(session(), previousCacheKey, removalLock);
                    if (success) {
                        final boolean put12 = cacheAccess.afterUpdate(session(), cacheKey, id, lock);
                        if (put12 && statistics.isStatisticsEnabled()) {
                            statistics.naturalIdCachePut(rootEntityDescriptor.getNavigableRole(), cacheAccess.getRegion().getName());
                        }
                    } else {
                        cacheAccess.unlockItem(session(), cacheKey, lock);
                    }
                });
                break;
            }
        default:
            {
                if (LOG.isDebugEnabled()) {
                    LOG.debug("Unexpected CachedNaturalIdValueSource [" + source + "]");
                }
            }
    }
}
Also used : EntityPersister(org.hibernate.persister.entity.EntityPersister) StatsHelper(org.hibernate.stat.internal.StatsHelper) AssertionFailure(org.hibernate.AssertionFailure) EntityPersister(org.hibernate.persister.entity.EntityPersister) Logger(org.jboss.logging.Logger) EventSource(org.hibernate.event.spi.EventSource) PersistenceContext(org.hibernate.engine.spi.PersistenceContext) NaturalIdResolutions(org.hibernate.engine.spi.NaturalIdResolutions) NaturalIdLogging(org.hibernate.metamodel.mapping.NaturalIdLogging) EntityMappingType(org.hibernate.metamodel.mapping.EntityMappingType) ArrayList(java.util.ArrayList) Map(java.util.Map) SessionFactoryImplementor(org.hibernate.engine.spi.SessionFactoryImplementor) LoadingLogger(org.hibernate.sql.results.LoadingLogger) Collection(java.util.Collection) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) StatisticsImplementor(org.hibernate.stat.spi.StatisticsImplementor) Resolution(org.hibernate.engine.spi.Resolution) Serializable(java.io.Serializable) Objects(java.util.Objects) List(java.util.List) SoftLock(org.hibernate.cache.spi.access.SoftLock) NaturalIdMapping(org.hibernate.metamodel.mapping.NaturalIdMapping) NaturalIdDataAccess(org.hibernate.cache.spi.access.NaturalIdDataAccess) CachedNaturalIdValueSource(org.hibernate.engine.spi.CachedNaturalIdValueSource) SharedSessionContractImplementor(org.hibernate.engine.spi.SharedSessionContractImplementor) EventSource(org.hibernate.event.spi.EventSource) SessionFactoryImplementor(org.hibernate.engine.spi.SessionFactoryImplementor) NaturalIdDataAccess(org.hibernate.cache.spi.access.NaturalIdDataAccess) StatisticsImplementor(org.hibernate.stat.spi.StatisticsImplementor) EntityMappingType(org.hibernate.metamodel.mapping.EntityMappingType) SoftLock(org.hibernate.cache.spi.access.SoftLock)

Example 29 with EntityMappingType

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

the class Builders method entityCalculated.

/**
 * Creates a EntityResultBuilder that does not allow any further configuring of the mapping.
 *
 * @see #entityCalculated(String, String, SessionFactoryImplementor)
 * @see NativeQuery#addEntity(String, Class, LockMode)
 * @see NativeQuery#addEntity(String, String, LockMode)
 */
public static DynamicResultBuilderEntityCalculated entityCalculated(String tableAlias, String entityName, LockMode explicitLockMode, SessionFactoryImplementor sessionFactory) {
    final RuntimeMetamodels runtimeMetamodels = sessionFactory.getRuntimeMetamodels();
    final EntityMappingType entityMapping = runtimeMetamodels.getEntityMappingType(entityName);
    return new DynamicResultBuilderEntityCalculated(entityMapping, tableAlias, explicitLockMode, sessionFactory);
}
Also used : RuntimeMetamodels(org.hibernate.metamodel.RuntimeMetamodels) EntityMappingType(org.hibernate.metamodel.mapping.EntityMappingType) DynamicResultBuilderEntityCalculated(org.hibernate.query.results.dynamic.DynamicResultBuilderEntityCalculated)

Example 30 with EntityMappingType

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

the class Builders method entity.

/**
 * Creates a EntityResultBuilder allowing for further configuring of the mapping.
 */
public static DynamicResultBuilderEntityStandard entity(String tableAlias, String entityName, SessionFactoryImplementor sessionFactory) {
    final RuntimeMetamodels runtimeMetamodels = sessionFactory.getRuntimeMetamodels();
    final EntityMappingType entityMapping = runtimeMetamodels.getEntityMappingType(entityName);
    return new DynamicResultBuilderEntityStandard(entityMapping, tableAlias);
}
Also used : RuntimeMetamodels(org.hibernate.metamodel.RuntimeMetamodels) EntityMappingType(org.hibernate.metamodel.mapping.EntityMappingType) DynamicResultBuilderEntityStandard(org.hibernate.query.results.dynamic.DynamicResultBuilderEntityStandard)

Aggregations

EntityMappingType (org.hibernate.metamodel.mapping.EntityMappingType)56 SessionFactoryImplementor (org.hibernate.engine.spi.SessionFactoryImplementor)19 PluralAttributeMapping (org.hibernate.metamodel.mapping.PluralAttributeMapping)16 TableGroup (org.hibernate.sql.ast.tree.from.TableGroup)16 Test (org.junit.jupiter.api.Test)16 EntityIdentifierMapping (org.hibernate.metamodel.mapping.EntityIdentifierMapping)15 EntityPersister (org.hibernate.persister.entity.EntityPersister)14 AttributeMapping (org.hibernate.metamodel.mapping.AttributeMapping)11 List (java.util.List)10 ModelPart (org.hibernate.metamodel.mapping.ModelPart)10 ArrayList (java.util.ArrayList)9 MappingMetamodel (org.hibernate.metamodel.MappingMetamodel)9 ColumnReference (org.hibernate.sql.ast.tree.expression.ColumnReference)8 TableReference (org.hibernate.sql.ast.tree.from.TableReference)8 BasicValuedModelPart (org.hibernate.metamodel.mapping.BasicValuedModelPart)7 StateArrayContributorMetadata (org.hibernate.metamodel.mapping.StateArrayContributorMetadata)7 ToOneAttributeMapping (org.hibernate.metamodel.mapping.internal.ToOneAttributeMapping)7 NavigablePath (org.hibernate.query.spi.NavigablePath)7 NamedTableReference (org.hibernate.sql.ast.tree.from.NamedTableReference)7 SelectStatement (org.hibernate.sql.ast.tree.select.SelectStatement)7