Search in sources :

Example 21 with EntityRegionAccessStrategy

use of org.hibernate.cache.spi.access.EntityRegionAccessStrategy in project hibernate-orm by hibernate.

the class MetamodelImpl method initialize.

/**
	 * Prepare the metamodel using the information from the collection of Hibernate
	 * {@link PersistentClass} models
	 *
	 * @param mappingMetadata The mapping information
	 * @param jpaMetaModelPopulationSetting Should the JPA Metamodel be built as well?
	 */
public void initialize(MetadataImplementor mappingMetadata, JpaMetaModelPopulationSetting jpaMetaModelPopulationSetting) {
    this.imports.putAll(mappingMetadata.getImports());
    final PersisterCreationContext persisterCreationContext = new PersisterCreationContext() {

        @Override
        public SessionFactoryImplementor getSessionFactory() {
            return sessionFactory;
        }

        @Override
        public MetadataImplementor getMetadata() {
            return mappingMetadata;
        }
    };
    final PersisterFactory persisterFactory = sessionFactory.getServiceRegistry().getService(PersisterFactory.class);
    for (final PersistentClass model : mappingMetadata.getEntityBindings()) {
        final EntityRegionAccessStrategy accessStrategy = sessionFactory.getCache().determineEntityRegionAccessStrategy(model);
        final NaturalIdRegionAccessStrategy naturalIdAccessStrategy = sessionFactory.getCache().determineNaturalIdRegionAccessStrategy(model);
        final EntityPersister cp = persisterFactory.createEntityPersister(model, accessStrategy, naturalIdAccessStrategy, persisterCreationContext);
        entityPersisterMap.put(model.getEntityName(), cp);
        if (cp.getConcreteProxyClass() != null && cp.getConcreteProxyClass().isInterface() && !Map.class.isAssignableFrom(cp.getConcreteProxyClass()) && cp.getMappedClass() != cp.getConcreteProxyClass()) {
            if (cp.getMappedClass().equals(cp.getConcreteProxyClass())) {
                // this part handles an odd case in the Hibernate test suite where we map an interface
                // as the class and the proxy.  I cannot think of a real life use case for that
                // specific test, but..
                log.debugf("Entity [%s] mapped same interface [%s] as class and proxy", cp.getEntityName(), cp.getMappedClass());
            } else {
                final String old = entityProxyInterfaceMap.put(cp.getConcreteProxyClass(), cp.getEntityName());
                if (old != null) {
                    throw new HibernateException(String.format(Locale.ENGLISH, "Multiple entities [%s, %s] named the same interface [%s] as their proxy which is not supported", old, cp.getEntityName(), cp.getConcreteProxyClass().getName()));
                }
            }
        }
    }
    for (final Collection model : mappingMetadata.getCollectionBindings()) {
        final CollectionRegionAccessStrategy accessStrategy = sessionFactory.getCache().determineCollectionRegionAccessStrategy(model);
        final CollectionPersister persister = persisterFactory.createCollectionPersister(model, accessStrategy, persisterCreationContext);
        collectionPersisterMap.put(model.getRole(), persister);
        Type indexType = persister.getIndexType();
        if (indexType != null && indexType.isAssociationType() && !indexType.isAnyType()) {
            String entityName = ((AssociationType) indexType).getAssociatedEntityName(sessionFactory);
            Set<String> roles = collectionRolesByEntityParticipant.get(entityName);
            if (roles == null) {
                roles = new HashSet<>();
                collectionRolesByEntityParticipant.put(entityName, roles);
            }
            roles.add(persister.getRole());
        }
        Type elementType = persister.getElementType();
        if (elementType.isAssociationType() && !elementType.isAnyType()) {
            String entityName = ((AssociationType) elementType).getAssociatedEntityName(sessionFactory);
            Set<String> roles = collectionRolesByEntityParticipant.get(entityName);
            if (roles == null) {
                roles = new HashSet<>();
                collectionRolesByEntityParticipant.put(entityName, roles);
            }
            roles.add(persister.getRole());
        }
    }
    // after *all* persisters and named queries are registered
    entityPersisterMap.values().forEach(EntityPersister::generateEntityDefinition);
    for (EntityPersister persister : entityPersisterMap.values()) {
        persister.postInstantiate();
        registerEntityNameResolvers(persister, entityNameResolvers);
    }
    collectionPersisterMap.values().forEach(CollectionPersister::postInstantiate);
    if (jpaMetaModelPopulationSetting != JpaMetaModelPopulationSetting.DISABLED) {
        MetadataContext context = new MetadataContext(sessionFactory, mappingMetadata.getMappedSuperclassMappingsCopy(), jpaMetaModelPopulationSetting);
        for (PersistentClass entityBinding : mappingMetadata.getEntityBindings()) {
            locateOrBuildEntityType(entityBinding, context);
        }
        handleUnusedMappedSuperclasses(context);
        context.wrapUp();
        this.jpaEntityTypeMap.putAll(context.getEntityTypeMap());
        this.jpaEmbeddableTypeMap.putAll(context.getEmbeddableTypeMap());
        this.jpaMappedSuperclassTypeMap.putAll(context.getMappedSuperclassTypeMap());
        this.jpaEntityTypesByEntityName.putAll(context.getEntityTypesByEntityName());
        applyNamedEntityGraphs(mappingMetadata.getNamedEntityGraphs().values());
    }
}
Also used : EntityPersister(org.hibernate.persister.entity.EntityPersister) HibernateException(org.hibernate.HibernateException) PersisterFactory(org.hibernate.persister.spi.PersisterFactory) EntityRegionAccessStrategy(org.hibernate.cache.spi.access.EntityRegionAccessStrategy) NaturalIdRegionAccessStrategy(org.hibernate.cache.spi.access.NaturalIdRegionAccessStrategy) CollectionRegionAccessStrategy(org.hibernate.cache.spi.access.CollectionRegionAccessStrategy) PersisterCreationContext(org.hibernate.persister.spi.PersisterCreationContext) ManagedType(javax.persistence.metamodel.ManagedType) MappedSuperclassType(javax.persistence.metamodel.MappedSuperclassType) EntityType(javax.persistence.metamodel.EntityType) AssociationType(org.hibernate.type.AssociationType) EmbeddableType(javax.persistence.metamodel.EmbeddableType) Type(org.hibernate.type.Type) CollectionPersister(org.hibernate.persister.collection.CollectionPersister) AssociationType(org.hibernate.type.AssociationType) Collection(org.hibernate.mapping.Collection) Map(java.util.Map) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) ConcurrentMap(java.util.concurrent.ConcurrentMap) PersistentClass(org.hibernate.mapping.PersistentClass)

Example 22 with EntityRegionAccessStrategy

use of org.hibernate.cache.spi.access.EntityRegionAccessStrategy in project hibernate-orm by hibernate.

the class AbstractEntityPersister method initializeLazyProperty.

public Object initializeLazyProperty(String fieldName, Object entity, SharedSessionContractImplementor session) {
    final EntityEntry entry = session.getPersistenceContext().getEntry(entity);
    final InterceptorImplementor interceptor = ((PersistentAttributeInterceptable) entity).$$_hibernate_getInterceptor();
    assert interceptor != null : "Expecting bytecode interceptor to be non-null";
    if (hasCollections()) {
        final Type type = getPropertyType(fieldName);
        if (type.isCollectionType()) {
            // we have a condition where a collection attribute is being access via enhancement:
            // 		we can circumvent all the rest and just return the PersistentCollection
            final CollectionType collectionType = (CollectionType) type;
            final CollectionPersister persister = factory.getMetamodel().collectionPersister(collectionType.getRole());
            // Get/create the collection, and make sure it is initialized!  This initialized part is
            // different from proxy-based scenarios where we have to create the PersistentCollection
            // reference "ahead of time" to add as a reference to the proxy.  For bytecode solutions
            // we are not creating the PersistentCollection ahead of time, but instead we are creating
            // it on first request through the enhanced entity.
            // see if there is already a collection instance associated with the session
            // 		NOTE : can this ever happen?
            final Serializable key = getCollectionKey(persister, entity, entry, session);
            PersistentCollection collection = session.getPersistenceContext().getCollection(new CollectionKey(persister, key));
            if (collection == null) {
                collection = collectionType.instantiate(session, persister, key);
                collection.setOwner(entity);
                session.getPersistenceContext().addUninitializedCollection(persister, collection, key);
            }
            // HHH-11161 Initialize, if the collection is not extra lazy
            if (!persister.isExtraLazy()) {
                session.initializeCollection(collection, false);
            }
            interceptor.attributeInitialized(fieldName);
            if (collectionType.isArrayType()) {
                session.getPersistenceContext().addCollectionHolder(collection);
            }
            // update the "state" of the entity's EntityEntry to over-write UNFETCHED_PROPERTY reference
            // for the collection to the just loaded collection
            final EntityEntry ownerEntry = session.getPersistenceContext().getEntry(entity);
            if (ownerEntry == null) {
                // not good
                throw new AssertionFailure("Could not locate EntityEntry for the collection owner in the PersistenceContext");
            }
            ownerEntry.overwriteLoadedStateCollectionValue(fieldName, collection);
            // EARLY EXIT!!!
            return collection;
        }
    }
    final Serializable id = session.getContextEntityIdentifier(entity);
    if (entry == null) {
        throw new HibernateException("entity is not associated with the session: " + id);
    }
    if (LOG.isTraceEnabled()) {
        LOG.tracev("Initializing lazy properties of: {0}, field access: {1}", MessageHelper.infoString(this, id, getFactory()), fieldName);
    }
    if (session.getCacheMode().isGetEnabled() && hasCache() && isLazyPropertiesCacheable()) {
        final EntityRegionAccessStrategy cache = getCacheAccessStrategy();
        final Object cacheKey = cache.generateCacheKey(id, this, session.getFactory(), session.getTenantIdentifier());
        final Object ce = CacheHelper.fromSharedCache(session, cacheKey, cache);
        if (ce != null) {
            final CacheEntry cacheEntry = (CacheEntry) getCacheEntryStructure().destructure(ce, factory);
            final Object initializedValue = initializeLazyPropertiesFromCache(fieldName, entity, session, entry, cacheEntry);
            interceptor.attributeInitialized(fieldName);
            // NOTE EARLY EXIT!!!
            return initializedValue;
        }
    }
    return initializeLazyPropertiesFromDatastore(fieldName, entity, session, id, entry);
}
Also used : Serializable(java.io.Serializable) AssertionFailure(org.hibernate.AssertionFailure) HibernateException(org.hibernate.HibernateException) PersistentAttributeInterceptable(org.hibernate.engine.spi.PersistentAttributeInterceptable) EntityRegionAccessStrategy(org.hibernate.cache.spi.access.EntityRegionAccessStrategy) CollectionKey(org.hibernate.engine.spi.CollectionKey) StructuredCacheEntry(org.hibernate.cache.spi.entry.StructuredCacheEntry) UnstructuredCacheEntry(org.hibernate.cache.spi.entry.UnstructuredCacheEntry) CacheEntry(org.hibernate.cache.spi.entry.CacheEntry) PersistentCollection(org.hibernate.collection.spi.PersistentCollection) EntityEntry(org.hibernate.engine.spi.EntityEntry) AssociationType(org.hibernate.type.AssociationType) JoinType(org.hibernate.sql.JoinType) CollectionType(org.hibernate.type.CollectionType) EntityType(org.hibernate.type.EntityType) ComponentType(org.hibernate.type.ComponentType) CompositeType(org.hibernate.type.CompositeType) VersionType(org.hibernate.type.VersionType) Type(org.hibernate.type.Type) CollectionPersister(org.hibernate.persister.collection.CollectionPersister) CollectionType(org.hibernate.type.CollectionType)

Example 23 with EntityRegionAccessStrategy

use of org.hibernate.cache.spi.access.EntityRegionAccessStrategy in project hibernate-orm by hibernate.

the class StatelessSessionImpl method refresh.

@Override
public void refresh(String entityName, Object entity, LockMode lockMode) {
    final EntityPersister persister = this.getEntityPersister(entityName, entity);
    final Serializable id = persister.getIdentifier(entity, this);
    if (LOG.isTraceEnabled()) {
        LOG.tracev("Refreshing transient {0}", MessageHelper.infoString(persister, id, this.getFactory()));
    }
    if (persister.hasCache()) {
        final EntityRegionAccessStrategy cache = persister.getCacheAccessStrategy();
        final Object ck = cache.generateCacheKey(id, persister, getFactory(), getTenantIdentifier());
        cache.evict(ck);
    }
    String previousFetchProfile = this.getLoadQueryInfluencers().getInternalFetchProfile();
    Object result = null;
    try {
        this.getLoadQueryInfluencers().setInternalFetchProfile("refresh");
        result = persister.load(id, entity, getNullSafeLockMode(lockMode), this);
    } finally {
        this.getLoadQueryInfluencers().setInternalFetchProfile(previousFetchProfile);
    }
    UnresolvableObjectException.throwIfNull(result, id, persister.getEntityName());
}
Also used : EntityPersister(org.hibernate.persister.entity.EntityPersister) Serializable(java.io.Serializable) EntityRegionAccessStrategy(org.hibernate.cache.spi.access.EntityRegionAccessStrategy)

Example 24 with EntityRegionAccessStrategy

use of org.hibernate.cache.spi.access.EntityRegionAccessStrategy in project hibernate-orm by hibernate.

the class CacheImpl method evictEntity.

@Override
public void evictEntity(String entityName, Serializable identifier) {
    EntityPersister p = sessionFactory.getMetamodel().entityPersister(entityName);
    if (p.hasCache()) {
        if (LOG.isDebugEnabled()) {
            LOG.debugf("Evicting second-level cache: %s", MessageHelper.infoString(p, identifier, sessionFactory));
        }
        EntityRegionAccessStrategy cache = p.getCacheAccessStrategy();
        // have to assume non tenancy
        Object key = cache.generateCacheKey(identifier, p, sessionFactory, null);
        cache.evict(key);
    }
}
Also used : EntityPersister(org.hibernate.persister.entity.EntityPersister) EntityRegionAccessStrategy(org.hibernate.cache.spi.access.EntityRegionAccessStrategy)

Aggregations

EntityRegionAccessStrategy (org.hibernate.cache.spi.access.EntityRegionAccessStrategy)24 EntityPersister (org.hibernate.persister.entity.EntityPersister)13 Serializable (java.io.Serializable)8 CollectionRegionAccessStrategy (org.hibernate.cache.spi.access.CollectionRegionAccessStrategy)5 CacheEntry (org.hibernate.cache.spi.entry.CacheEntry)5 EntityEntry (org.hibernate.engine.spi.EntityEntry)5 AssertionFailure (org.hibernate.AssertionFailure)4 SessionFactoryImplementor (org.hibernate.engine.spi.SessionFactoryImplementor)4 SharedSessionContractImplementor (org.hibernate.engine.spi.SharedSessionContractImplementor)4 SoftLock (org.hibernate.cache.spi.access.SoftLock)3 PersistenceContext (org.hibernate.engine.spi.PersistenceContext)3 Type (org.hibernate.type.Type)3 HibernateException (org.hibernate.HibernateException)2 LockMode (org.hibernate.LockMode)2 CollectionPersister (org.hibernate.persister.collection.CollectionPersister)2 AssociationType (org.hibernate.type.AssociationType)2 Map (java.util.Map)1 ConcurrentHashMap (java.util.concurrent.ConcurrentHashMap)1 ConcurrentMap (java.util.concurrent.ConcurrentMap)1 EmbeddableType (javax.persistence.metamodel.EmbeddableType)1