Search in sources :

Example 46 with MappingMetamodelImplementor

use of org.hibernate.metamodel.spi.MappingMetamodelImplementor in project hibernate-orm by hibernate.

the class CollectionCacheInvalidator method evictCache.

private void evictCache(Object entity, EntityPersister persister, EventSource session, Object[] oldState) {
    try {
        SessionFactoryImplementor factory = persister.getFactory();
        final MappingMetamodelImplementor metamodel = factory.getRuntimeMetamodels().getMappingMetamodel();
        Set<String> collectionRoles = metamodel.getCollectionRolesByEntityParticipant(persister.getEntityName());
        if (collectionRoles == null || collectionRoles.isEmpty()) {
            return;
        }
        final EntityMetamodel entityMetamodel = persister.getEntityMetamodel();
        final boolean debugEnabled = LOG.isDebugEnabled();
        for (String role : collectionRoles) {
            final CollectionPersister collectionPersister = metamodel.getCollectionDescriptor(role);
            if (!collectionPersister.hasCache()) {
                // ignore collection if no caching is used
                continue;
            }
            // this is the property this OneToMany relation is mapped by
            String mappedBy = collectionPersister.getMappedByProperty();
            if (!collectionPersister.isManyToMany() && mappedBy != null && !mappedBy.isEmpty()) {
                int i = entityMetamodel.getPropertyIndex(mappedBy);
                Object oldId = null;
                if (oldState != null) {
                    // in case of updating an entity we perhaps have to decache 2 entity collections, this is the
                    // old one
                    oldId = getIdentifier(session, oldState[i]);
                }
                Object ref = persister.getValue(entity, i);
                Object id = getIdentifier(session, ref);
                // only evict if the related entity has changed
                if ((id != null && !id.equals(oldId)) || (oldId != null && !oldId.equals(id))) {
                    if (id != null) {
                        evict(id, collectionPersister, session);
                    }
                    if (oldId != null) {
                        evict(oldId, collectionPersister, session);
                    }
                }
            } else {
                if (debugEnabled) {
                    LOG.debug("Evict CollectionRegion " + role);
                }
                final CollectionDataAccess cacheAccessStrategy = collectionPersister.getCacheAccessStrategy();
                final SoftLock softLock = cacheAccessStrategy.lockRegion();
                session.getActionQueue().registerProcess((success, session1) -> cacheAccessStrategy.unlockRegion(softLock));
            }
        }
    } catch (Exception e) {
        if (PROPAGATE_EXCEPTION) {
            throw new IllegalStateException(e);
        }
        // don't let decaching influence other logic
        LOG.error("", e);
    }
}
Also used : SessionFactoryImplementor(org.hibernate.engine.spi.SessionFactoryImplementor) CollectionDataAccess(org.hibernate.cache.spi.access.CollectionDataAccess) HibernateException(org.hibernate.HibernateException) CollectionPersister(org.hibernate.persister.collection.CollectionPersister) MappingMetamodelImplementor(org.hibernate.metamodel.spi.MappingMetamodelImplementor) EntityMetamodel(org.hibernate.tuple.entity.EntityMetamodel) SoftLock(org.hibernate.cache.spi.access.SoftLock)

Example 47 with MappingMetamodelImplementor

use of org.hibernate.metamodel.spi.MappingMetamodelImplementor in project hibernate-orm by hibernate.

the class DefaultRefreshEventListener method evictCachedCollections.

private void evictCachedCollections(Type[] types, Object id, EventSource source) throws HibernateException {
    final ActionQueue actionQueue = source.getActionQueue();
    final SessionFactoryImplementor factory = source.getFactory();
    final MappingMetamodelImplementor metamodel = factory.getRuntimeMetamodels().getMappingMetamodel();
    for (Type type : types) {
        if (type.isCollectionType()) {
            final String role = ((CollectionType) type).getRole();
            CollectionPersister collectionPersister = metamodel.getCollectionDescriptor(role);
            if (collectionPersister.hasCache()) {
                final CollectionDataAccess cache = collectionPersister.getCacheAccessStrategy();
                final Object ck = cache.generateCacheKey(id, collectionPersister, factory, source.getTenantIdentifier());
                final SoftLock lock = cache.lockItem(source, ck, null);
                cache.remove(source, ck);
                actionQueue.registerProcess((success, session) -> cache.unlockItem(session, ck, lock));
            }
        } else if (type.isComponentType()) {
            CompositeType compositeType = (CompositeType) type;
            evictCachedCollections(compositeType.getSubtypes(), id, source);
        }
    }
}
Also used : ActionQueue(org.hibernate.engine.spi.ActionQueue) CollectionType(org.hibernate.type.CollectionType) CompositeType(org.hibernate.type.CompositeType) Type(org.hibernate.type.Type) CollectionPersister(org.hibernate.persister.collection.CollectionPersister) SessionFactoryImplementor(org.hibernate.engine.spi.SessionFactoryImplementor) CollectionType(org.hibernate.type.CollectionType) MappingMetamodelImplementor(org.hibernate.metamodel.spi.MappingMetamodelImplementor) CollectionDataAccess(org.hibernate.cache.spi.access.CollectionDataAccess) SoftLock(org.hibernate.cache.spi.access.SoftLock) CompositeType(org.hibernate.type.CompositeType)

Example 48 with MappingMetamodelImplementor

use of org.hibernate.metamodel.spi.MappingMetamodelImplementor in project hibernate-orm by hibernate.

the class UnionSubclassEntityPersister method generateSubquery.

protected String generateSubquery(Set<String> treated) {
    if (!hasSubclasses()) {
        return getTableName();
    }
    final Dialect dialect = getFactory().getJdbcServices().getDialect();
    final MappingMetamodelImplementor metamodel = getFactory().getRuntimeMetamodels().getMappingMetamodel();
    // Collect all selectables of every entity subtype and group by selection expression as well as table name
    final LinkedHashMap<String, Map<String, SelectableMapping>> selectables = new LinkedHashMap<>();
    final SelectableConsumer selectableConsumer = (i, selectable) -> {
        selectables.computeIfAbsent(selectable.getSelectionExpression(), k -> new HashMap<>()).put(selectable.getContainingTableExpression(), selectable);
    };
    // Collect the concrete subclass table names for the treated entity names
    final Set<String> treatedTableNames = new HashSet<>(treated.size());
    for (String subclassName : treated) {
        final UnionSubclassEntityPersister subPersister = (UnionSubclassEntityPersister) metamodel.getEntityDescriptor(subclassName);
        for (String subclassTableName : subPersister.getSubclassTableNames()) {
            if (ArrayHelper.indexOf(subclassSpaces, subclassTableName) != -1) {
                treatedTableNames.add(subclassTableName);
            }
        }
        subPersister.getIdentifierMapping().forEachSelectable(selectableConsumer);
        if (subPersister.getVersionMapping() != null) {
            subPersister.getVersionMapping().forEachSelectable(selectableConsumer);
        }
        subPersister.visitSubTypeAttributeMappings(attributeMapping -> attributeMapping.forEachSelectable(selectableConsumer));
    }
    // Create a union sub-query for the table names, like generateSubquery(PersistentClass model, Mapping mapping)
    final StringBuilder buf = new StringBuilder(subquery.length()).append("( ");
    for (String name : getSubclassEntityNames()) {
        final AbstractEntityPersister persister = (AbstractEntityPersister) metamodel.findEntityDescriptor(name);
        final String subclassTableName = persister.getTableName();
        if (treatedTableNames.contains(subclassTableName)) {
            buf.append("select ");
            for (Map<String, SelectableMapping> selectableMappings : selectables.values()) {
                SelectableMapping selectableMapping = selectableMappings.get(subclassTableName);
                if (selectableMapping == null) {
                    // If there is no selectable mapping for a table name, we render a null expression
                    selectableMapping = selectableMappings.values().iterator().next();
                    final int sqlType = selectableMapping.getJdbcMapping().getJdbcType().getDefaultSqlTypeCode();
                    buf.append(dialect.getSelectClauseNullString(sqlType)).append(" as ");
                }
                buf.append(new ColumnReference((String) null, selectableMapping, getFactory()).getExpressionText());
                buf.append(", ");
            }
            buf.append(persister.getDiscriminatorSQLValue()).append(" as clazz_");
            buf.append(" from ").append(subclassTableName);
            buf.append(" union ");
            if (dialect.supportsUnionAll()) {
                buf.append("all ");
            }
        }
    }
    if (buf.length() > 2) {
        // chop the last union (all)
        buf.setLength(buf.length() - (dialect.supportsUnionAll() ? 11 : 7));
    }
    return buf.append(" )").toString();
}
Also used : BasicType(org.hibernate.type.BasicType) MappingMetamodelImplementor(org.hibernate.metamodel.spi.MappingMetamodelImplementor) IdentityGenerator(org.hibernate.id.IdentityGenerator) JoinedList(org.hibernate.internal.util.collections.JoinedList) SqlAstCreationContext(org.hibernate.sql.ast.spi.SqlAstCreationContext) PersistentClass(org.hibernate.mapping.PersistentClass) ExecuteUpdateResultCheckStyle(org.hibernate.engine.spi.ExecuteUpdateResultCheckStyle) Map(java.util.Map) SessionFactoryImplementor(org.hibernate.engine.spi.SessionFactoryImplementor) Column(org.hibernate.mapping.Column) NavigablePath(org.hibernate.query.spi.NavigablePath) Set(java.util.Set) Subclass(org.hibernate.mapping.Subclass) SqlAliasBase(org.hibernate.sql.ast.spi.SqlAliasBase) Serializable(java.io.Serializable) SqlExpressionResolver(org.hibernate.sql.ast.spi.SqlExpressionResolver) ArrayHelper(org.hibernate.internal.util.collections.ArrayHelper) List(java.util.List) PersisterCreationContext(org.hibernate.persister.spi.PersisterCreationContext) Dialect(org.hibernate.dialect.Dialect) RuntimeModelCreationContext(org.hibernate.metamodel.spi.RuntimeModelCreationContext) MappingException(org.hibernate.MappingException) HibernateException(org.hibernate.HibernateException) SelectableConsumer(org.hibernate.metamodel.mapping.SelectableConsumer) AssertionFailure(org.hibernate.AssertionFailure) SqlStringGenerationContext(org.hibernate.boot.model.relational.SqlStringGenerationContext) ColumnReference(org.hibernate.sql.ast.tree.expression.ColumnReference) HashMap(java.util.HashMap) EntityDataAccess(org.hibernate.cache.spi.access.EntityDataAccess) Metadata(org.hibernate.boot.Metadata) Supplier(java.util.function.Supplier) ArrayList(java.util.ArrayList) HashSet(java.util.HashSet) LinkedHashMap(java.util.LinkedHashMap) UnionTableGroup(org.hibernate.sql.ast.tree.from.UnionTableGroup) NamedTableReference(org.hibernate.sql.ast.tree.from.NamedTableReference) StaticFilterAliasGenerator(org.hibernate.internal.StaticFilterAliasGenerator) UnionTableReference(org.hibernate.sql.ast.tree.from.UnionTableReference) FilterAliasGenerator(org.hibernate.internal.FilterAliasGenerator) LinkedHashSet(java.util.LinkedHashSet) Predicate(org.hibernate.sql.ast.tree.predicate.Predicate) Iterator(java.util.Iterator) EntityDiscriminatorMapping(org.hibernate.metamodel.mapping.EntityDiscriminatorMapping) Table(org.hibernate.mapping.Table) MappingModelCreationProcess(org.hibernate.metamodel.mapping.internal.MappingModelCreationProcess) Consumer(java.util.function.Consumer) StandardBasicTypes(org.hibernate.type.StandardBasicTypes) FromClauseAccess(org.hibernate.sql.ast.spi.FromClauseAccess) SelectableMapping(org.hibernate.metamodel.mapping.SelectableMapping) NaturalIdDataAccess(org.hibernate.cache.spi.access.NaturalIdDataAccess) Collections(java.util.Collections) TableGroup(org.hibernate.sql.ast.tree.from.TableGroup) Type(org.hibernate.type.Type) SelectableMapping(org.hibernate.metamodel.mapping.SelectableMapping) SelectableConsumer(org.hibernate.metamodel.mapping.SelectableConsumer) LinkedHashMap(java.util.LinkedHashMap) Dialect(org.hibernate.dialect.Dialect) MappingMetamodelImplementor(org.hibernate.metamodel.spi.MappingMetamodelImplementor) Map(java.util.Map) HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap) HashSet(java.util.HashSet) LinkedHashSet(java.util.LinkedHashSet) ColumnReference(org.hibernate.sql.ast.tree.expression.ColumnReference)

Example 49 with MappingMetamodelImplementor

use of org.hibernate.metamodel.spi.MappingMetamodelImplementor in project hibernate-orm by hibernate.

the class Util method resolveResultSetMappingClasses.

public static void resolveResultSetMappingClasses(Class[] resultSetMappingClasses, ResultSetMapping resultSetMapping, Consumer<String> querySpaceConsumer, ResultSetMappingResolutionContext context) {
    final MappingMetamodelImplementor mappingMetamodel = context.getSessionFactory().getRuntimeMetamodels().getMappingMetamodel();
    final JavaTypeRegistry javaTypeRegistry = mappingMetamodel.getTypeConfiguration().getJavaTypeRegistry();
    for (Class<?> resultSetMappingClass : resultSetMappingClasses) {
        final EntityPersister entityDescriptor = mappingMetamodel.findEntityDescriptor(resultSetMappingClass);
        if (entityDescriptor != null) {
            resultSetMapping.addResultBuilder(new EntityDomainResultBuilder(entityDescriptor));
            for (String querySpace : entityDescriptor.getSynchronizedQuerySpaces()) {
                querySpaceConsumer.accept(querySpace);
            }
        } else {
            final JavaType<?> basicType = javaTypeRegistry.getDescriptor(resultSetMappingClass);
            if (basicType != null) {
                resultSetMapping.addResultBuilder(new ScalarDomainResultBuilder<>(basicType));
            }
        }
    }
}
Also used : EntityPersister(org.hibernate.persister.entity.EntityPersister) JavaTypeRegistry(org.hibernate.type.descriptor.java.spi.JavaTypeRegistry) MappingMetamodelImplementor(org.hibernate.metamodel.spi.MappingMetamodelImplementor)

Aggregations

MappingMetamodelImplementor (org.hibernate.metamodel.spi.MappingMetamodelImplementor)49 EntityPersister (org.hibernate.persister.entity.EntityPersister)40 Test (org.junit.jupiter.api.Test)37 BasicAttributeMapping (org.hibernate.metamodel.mapping.internal.BasicAttributeMapping)36 JdbcMapping (org.hibernate.metamodel.mapping.JdbcMapping)29 JdbcTypeRegistry (org.hibernate.type.descriptor.jdbc.spi.JdbcTypeRegistry)14 BitSet (java.util.BitSet)7 SessionFactoryImplementor (org.hibernate.engine.spi.SessionFactoryImplementor)6 CollectionPersister (org.hibernate.persister.collection.CollectionPersister)4 Dialect (org.hibernate.dialect.Dialect)3 Type (org.hibernate.type.Type)3 ArrayList (java.util.ArrayList)2 HashSet (java.util.HashSet)2 EntityNameResolver (org.hibernate.EntityNameResolver)2 HibernateException (org.hibernate.HibernateException)2 CollectionDataAccess (org.hibernate.cache.spi.access.CollectionDataAccess)2 SoftLock (org.hibernate.cache.spi.access.SoftLock)2 EntityEntry (org.hibernate.engine.spi.EntityEntry)2 JpaAttributeConverter (org.hibernate.metamodel.model.convert.spi.JpaAttributeConverter)2 NamedTableReference (org.hibernate.sql.ast.tree.from.NamedTableReference)2