Search in sources :

Example 11 with ReactiveEntityPersister

use of org.hibernate.reactive.persister.entity.impl.ReactiveEntityPersister in project hibernate-reactive by hibernate.

the class ReactiveStatelessSessionImpl method reactiveGet.

@Override
public <T> CompletionStage<T> reactiveGet(Class<? extends T> entityClass, Object id, LockMode lockMode, EntityGraph<T> fetchGraph) {
    checkOpen();
    if (fetchGraph != null) {
        getLoadQueryInfluencers().getEffectiveEntityGraph().applyGraph((RootGraphImplementor<T>) fetchGraph, GraphSemantic.FETCH);
    }
    ReactiveEntityPersister persister = (ReactiveEntityPersister) getFactory().getMetamodel().entityPersister(entityClass);
    LockOptions lockOptions = getNullSafeLockOptions(lockMode);
    return persister.reactiveLoad((Serializable) id, null, lockOptions, this).whenComplete((v, e) -> {
        if (getPersistenceContext().isLoadFinished()) {
            getPersistenceContext().clear();
        }
        getLoadQueryInfluencers().getEffectiveEntityGraph().clear();
    }).thenApply(entity -> (T) entity);
}
Also used : CompletionStages.completedFuture(org.hibernate.reactive.util.impl.CompletionStages.completedFuture) BatchingConnection(org.hibernate.reactive.pool.BatchingConnection) NamedQueryDefinition(org.hibernate.engine.spi.NamedQueryDefinition) EntityPersister(org.hibernate.persister.entity.EntityPersister) NativeQueryTupleTransformer(org.hibernate.jpa.spi.NativeQueryTupleTransformer) GraphSemantic(org.hibernate.graph.GraphSemantic) IdentifierGeneration.assignIdIfNecessary(org.hibernate.reactive.id.impl.IdentifierGeneration.assignIdIfNecessary) Log(org.hibernate.reactive.logging.impl.Log) PersistenceContext(org.hibernate.engine.spi.PersistenceContext) LoggerFactory(org.hibernate.reactive.logging.impl.LoggerFactory) PersistentCollection(org.hibernate.collection.spi.PersistentCollection) SQLCustomQuery(org.hibernate.loader.custom.sql.SQLCustomQuery) ReactiveCustomLoader(org.hibernate.reactive.loader.custom.impl.ReactiveCustomLoader) HibernateProxy(org.hibernate.proxy.HibernateProxy) CustomQuery(org.hibernate.loader.custom.CustomQuery) HQLQueryPlan(org.hibernate.engine.query.spi.HQLQueryPlan) SessionFactoryImpl(org.hibernate.internal.SessionFactoryImpl) ReactiveNativeQuery(org.hibernate.reactive.session.ReactiveNativeQuery) BytecodeEnhancementMetadata(org.hibernate.bytecode.spi.BytecodeEnhancementMetadata) EntityGraph(javax.persistence.EntityGraph) ParameterMetadata(org.hibernate.query.ParameterMetadata) LockOptions(org.hibernate.LockOptions) MethodHandles(java.lang.invoke.MethodHandles) ResultSetMapping(org.hibernate.reactive.common.ResultSetMapping) ReactiveStatelessSession(org.hibernate.reactive.session.ReactiveStatelessSession) Serializable(java.io.Serializable) List(java.util.List) CompletionStages.failedFuture(org.hibernate.reactive.util.impl.CompletionStages.failedFuture) CompletionStage(java.util.concurrent.CompletionStage) Dialect(org.hibernate.dialect.Dialect) CompletionStages.loop(org.hibernate.reactive.util.impl.CompletionStages.loop) ReactiveEntityPersister(org.hibernate.reactive.persister.entity.impl.ReactiveEntityPersister) HibernateException(org.hibernate.HibernateException) SharedSessionContractImplementor(org.hibernate.engine.spi.SharedSessionContractImplementor) Criteria(org.hibernate.reactive.session.Criteria) NamedSQLQueryDefinition(org.hibernate.engine.spi.NamedSQLQueryDefinition) SessionUtil.checkEntityFound(org.hibernate.reactive.session.impl.SessionUtil.checkEntityFound) RootGraphImpl(org.hibernate.graph.internal.RootGraphImpl) EntityDataAccess(org.hibernate.cache.spi.access.EntityDataAccess) CompletableFuture(java.util.concurrent.CompletableFuture) UnresolvableObjectException(org.hibernate.UnresolvableObjectException) RootGraphImplementor(org.hibernate.graph.spi.RootGraphImplementor) CriteriaQueryTupleTransformer(org.hibernate.jpa.spi.CriteriaQueryTupleTransformer) ReactiveQuery(org.hibernate.reactive.session.ReactiveQuery) IdentifierGeneration.generateId(org.hibernate.reactive.id.impl.IdentifierGeneration.generateId) BulkOperationCleanupAction(org.hibernate.action.internal.BulkOperationCleanupAction) StatelessSessionImpl(org.hibernate.internal.StatelessSessionImpl) MetamodelImplementor(org.hibernate.metamodel.spi.MetamodelImplementor) Tuple(javax.persistence.Tuple) QueryParameters(org.hibernate.engine.spi.QueryParameters) LockMode(org.hibernate.LockMode) LazyInitializer(org.hibernate.proxy.LazyInitializer) Versioning(org.hibernate.engine.internal.Versioning) ReactiveCollectionPersister(org.hibernate.reactive.persister.collection.impl.ReactiveCollectionPersister) EntityKey(org.hibernate.engine.spi.EntityKey) EntityMetamodel(org.hibernate.tuple.entity.EntityMetamodel) CriteriaQueryOptions(org.hibernate.reactive.session.CriteriaQueryOptions) ReactivePersistenceContextAdapter(org.hibernate.reactive.engine.impl.ReactivePersistenceContextAdapter) SessionCreationOptions(org.hibernate.internal.SessionCreationOptions) NativeSQLQuerySpecification(org.hibernate.engine.query.spi.sql.NativeSQLQuerySpecification) ReactiveConnection(org.hibernate.reactive.pool.ReactiveConnection) LockOptions(org.hibernate.LockOptions) ReactiveEntityPersister(org.hibernate.reactive.persister.entity.impl.ReactiveEntityPersister)

Example 12 with ReactiveEntityPersister

use of org.hibernate.reactive.persister.entity.impl.ReactiveEntityPersister in project hibernate-reactive by hibernate.

the class DefaultReactiveLockEventListener method doUpgradeLock.

private CompletionStage<Void> doUpgradeLock(Object object, EntityEntry entry, LockOptions lockOptions, EventSource source) {
    final EntityPersister persister = entry.getPersister();
    final boolean canWriteToCache = persister.canWriteToCache();
    final SoftLock lock;
    final Object cacheKey;
    if (canWriteToCache) {
        EntityDataAccess cache = persister.getCacheAccessStrategy();
        cacheKey = cache.generateCacheKey(entry.getId(), persister, source.getFactory(), source.getTenantIdentifier());
        lock = cache.lockItem(source, cacheKey, entry.getVersion());
    } else {
        cacheKey = null;
        lock = null;
    }
    try {
        return ((ReactiveEntityPersister) persister).lockReactive(entry.getId(), entry.getVersion(), object, lockOptions, source).thenAccept(v -> entry.setLockMode(lockOptions.getLockMode())).whenComplete((r, e) -> {
            // so release the soft lock
            if (canWriteToCache) {
                persister.getCacheAccessStrategy().unlockItem(source, cacheKey, lock);
            }
        });
    } catch (HibernateException he) {
        // in case lockReactive() throws an exception
        if (canWriteToCache) {
            persister.getCacheAccessStrategy().unlockItem(source, cacheKey, lock);
        }
        throw he;
    }
}
Also used : EntityPersister(org.hibernate.persister.entity.EntityPersister) ReactiveEntityPersister(org.hibernate.reactive.persister.entity.impl.ReactiveEntityPersister) CompletionStages.completedFuture(org.hibernate.reactive.util.impl.CompletionStages.completedFuture) EntityPersister(org.hibernate.persister.entity.EntityPersister) EventSource(org.hibernate.event.spi.EventSource) EntityDataAccess(org.hibernate.cache.spi.access.EntityDataAccess) Log(org.hibernate.reactive.logging.impl.Log) PersistenceContext(org.hibernate.engine.spi.PersistenceContext) LoggerFactory(org.hibernate.reactive.logging.impl.LoggerFactory) ObjectDeletedException(org.hibernate.ObjectDeletedException) LockEvent(org.hibernate.event.spi.LockEvent) Cascade(org.hibernate.reactive.engine.impl.Cascade) Status(org.hibernate.engine.spi.Status) CompletionStages.voidFuture(org.hibernate.reactive.util.impl.CompletionStages.voidFuture) ReactiveSession(org.hibernate.reactive.session.ReactiveSession) LockMode(org.hibernate.LockMode) LockOptions(org.hibernate.LockOptions) LockEventListener(org.hibernate.event.spi.LockEventListener) ReactiveEntityIncrementVersionProcess(org.hibernate.reactive.engine.impl.ReactiveEntityIncrementVersionProcess) MethodHandles(java.lang.invoke.MethodHandles) ForeignKeys(org.hibernate.reactive.engine.impl.ForeignKeys) ReactiveEntityVerifyVersionProcess(org.hibernate.reactive.engine.impl.ReactiveEntityVerifyVersionProcess) Serializable(java.io.Serializable) TransientObjectException(org.hibernate.TransientObjectException) MessageHelper.infoString(org.hibernate.pretty.MessageHelper.infoString) SoftLock(org.hibernate.cache.spi.access.SoftLock) CascadingActions(org.hibernate.reactive.engine.impl.CascadingActions) CompletionStage(java.util.concurrent.CompletionStage) ReactiveLockEventListener(org.hibernate.reactive.event.ReactiveLockEventListener) AbstractReassociateEventListener(org.hibernate.event.internal.AbstractReassociateEventListener) EntityEntry(org.hibernate.engine.spi.EntityEntry) CascadePoint(org.hibernate.engine.internal.CascadePoint) SessionImplementor(org.hibernate.engine.spi.SessionImplementor) ReactiveEntityPersister(org.hibernate.reactive.persister.entity.impl.ReactiveEntityPersister) HibernateException(org.hibernate.HibernateException) ReactiveEntityPersister(org.hibernate.reactive.persister.entity.impl.ReactiveEntityPersister) HibernateException(org.hibernate.HibernateException) SoftLock(org.hibernate.cache.spi.access.SoftLock) EntityDataAccess(org.hibernate.cache.spi.access.EntityDataAccess)

Example 13 with ReactiveEntityPersister

use of org.hibernate.reactive.persister.entity.impl.ReactiveEntityPersister in project hibernate-reactive by hibernate.

the class DefaultReactiveLoadEventListener method loadFromDatasource.

/**
 * Performs the process of loading an entity from the configured
 * underlying datasource.
 *
 * @param event The load event
 * @param persister The persister for the entity being requested for load
 *
 * @return The object loaded from the datasource, or null if not found.
 */
protected CompletionStage<Object> loadFromDatasource(LoadEvent event, EntityPersister persister) {
    CompletionStage<Object> entity = ((ReactiveEntityPersister) persister).reactiveLoad(event.getEntityId(), event.getInstanceToLoad(), event.getLockOptions(), event.getSession());
    final StatisticsImplementor statistics = event.getSession().getFactory().getStatistics();
    if (event.isAssociationFetch() && statistics.isStatisticsEnabled()) {
        statistics.fetchEntity(event.getEntityClassName());
    }
    return entity;
}
Also used : ReactiveEntityPersister(org.hibernate.reactive.persister.entity.impl.ReactiveEntityPersister) StatisticsImplementor(org.hibernate.stat.spi.StatisticsImplementor)

Example 14 with ReactiveEntityPersister

use of org.hibernate.reactive.persister.entity.impl.ReactiveEntityPersister in project hibernate-reactive by hibernate.

the class EntityTypes method loadByUniqueKey.

/**
 * Load an instance by a unique key that is not the primary key.
 *
 * @param entityType The {@link EntityType} of the association
 * @param key The unique key property value.
 * @param session The originating session.
 *
 * @return The loaded entity
 *
 * @throws HibernateException generally indicates problems performing the load.
 */
static CompletionStage<Object> loadByUniqueKey(EntityType entityType, Object key, SharedSessionContractImplementor session) throws HibernateException {
    SessionFactoryImplementor factory = session.getFactory();
    String entityName = entityType.getAssociatedEntityName();
    String uniqueKeyPropertyName = entityType.getRHSUniqueKeyPropertyName();
    ReactiveEntityPersister persister = (ReactiveEntityPersister) factory.getMetamodel().entityPersister(entityName);
    // TODO: implement 2nd level caching?! natural id caching ?! proxies?!
    EntityUniqueKey euk = new EntityUniqueKey(entityName, uniqueKeyPropertyName, key, entityType.getIdentifierOrUniqueKeyType(factory), persister.getEntityMode(), factory);
    PersistenceContext persistenceContext = session.getPersistenceContextInternal();
    Object result = persistenceContext.getEntity(euk);
    if (result != null) {
        return completedFuture(persistenceContext.proxyFor(result));
    } else {
        return persister.reactiveLoadByUniqueKey(uniqueKeyPropertyName, key, session).thenApply(loaded -> {
            // add it to the Persistence Context
            if (loaded != null) {
                persistenceContext.addEntity(euk, loaded);
            }
            return loaded;
        });
    }
}
Also used : ReactiveEntityPersister(org.hibernate.reactive.persister.entity.impl.ReactiveEntityPersister) EntityUniqueKey(org.hibernate.engine.spi.EntityUniqueKey) SessionFactoryImplementor(org.hibernate.engine.spi.SessionFactoryImplementor) PersistenceContext(org.hibernate.engine.spi.PersistenceContext)

Example 15 with ReactiveEntityPersister

use of org.hibernate.reactive.persister.entity.impl.ReactiveEntityPersister in project hibernate-reactive by hibernate.

the class ReactiveEntityUpdateAction method reactiveExecute.

@Override
public CompletionStage<Void> reactiveExecute() throws HibernateException {
    final Serializable id = getId();
    final EntityPersister persister = getPersister();
    final SharedSessionContractImplementor session = getSession();
    final Object instance = getInstance();
    final boolean veto = preUpdate();
    final SessionFactoryImplementor factory = session.getFactory();
    Object previousVersion = getPreviousVersion();
    if (persister.isVersionPropertyGenerated()) {
        // we need to grab the version value from the entity, otherwise
        // we have issues with generated-version entities that may have
        // multiple actions queued during the same flush
        previousVersion = persister.getVersion(instance);
    }
    final Object ck;
    if (persister.canWriteToCache()) {
        final EntityDataAccess cache = persister.getCacheAccessStrategy();
        ck = cache.generateCacheKey(id, persister, factory, session.getTenantIdentifier());
        setLock(cache.lockItem(session, ck, previousVersion));
    } else {
        ck = null;
    }
    ReactiveEntityPersister reactivePersister = (ReactiveEntityPersister) persister;
    CompletionStage<Void> update = veto ? voidFuture() : reactivePersister.updateReactive(id, getState(), getDirtyFields(), hasDirtyCollection(), getPreviousState(), previousVersion, instance, getRowId(), session);
    return update.thenApply(res -> {
        final EntityEntry entry = session.getPersistenceContextInternal().getEntry(instance);
        if (entry == null) {
            throw new AssertionFailure("possible non-threadsafe access to session");
        }
        return entry;
    }).thenCompose(entry -> {
        if (entry.getStatus() == Status.MANAGED || persister.isVersionPropertyGenerated()) {
            // get the updated snapshot of the entity state by cloning current state;
            // it is safe to copy in place, since by this time no-one else (should have)
            // has a reference  to the array
            TypeHelper.deepCopy(getState(), persister.getPropertyTypes(), persister.getPropertyCheckability(), getState(), session);
            return processGeneratedProperties(id, reactivePersister, session, instance).thenAccept(v -> entry.postUpdate(instance, getState(), getNextVersion())).thenApply(v -> entry);
        }
        return completedFuture(entry);
    }).thenAccept(entry -> {
        final StatisticsImplementor statistics = factory.getStatistics();
        if (persister.canWriteToCache()) {
            if (persister.isCacheInvalidationRequired() || entry.getStatus() != Status.MANAGED) {
                persister.getCacheAccessStrategy().remove(session, ck);
            } else if (session.getCacheMode().isPutEnabled()) {
                // TODO: inefficient if that cache is just going to ignore the updated state!
                final CacheEntry ce = persister.buildCacheEntry(instance, getState(), getNextVersion(), getSession());
                setCacheEntry(persister.getCacheEntryStructure().structure(ce));
                final boolean put = cacheUpdate(persister, getPreviousVersion(), ck);
                if (put && statistics.isStatisticsEnabled()) {
                    statistics.entityCachePut(StatsHelper.INSTANCE.getRootEntityRole(persister), getPersister().getCacheAccessStrategy().getRegion().getName());
                }
            }
        }
        session.getPersistenceContextInternal().getNaturalIdHelper().manageSharedNaturalIdCrossReference(persister, id, getState(), getPreviousNaturalIdValues(), CachedNaturalIdValueSource.UPDATE);
        postUpdate();
        if (statistics.isStatisticsEnabled() && !veto) {
            statistics.updateEntity(getPersister().getEntityName());
        }
    });
}
Also used : EntityPersister(org.hibernate.persister.entity.EntityPersister) ReactiveEntityPersister(org.hibernate.reactive.persister.entity.impl.ReactiveEntityPersister) CacheEntry(org.hibernate.cache.spi.entry.CacheEntry) StatsHelper(org.hibernate.stat.internal.StatsHelper) CompletionStages.completedFuture(org.hibernate.reactive.util.impl.CompletionStages.completedFuture) AssertionFailure(org.hibernate.AssertionFailure) org.hibernate.engine.spi(org.hibernate.engine.spi) EntityPersister(org.hibernate.persister.entity.EntityPersister) ReactiveExecutable(org.hibernate.reactive.engine.ReactiveExecutable) EntityDataAccess(org.hibernate.cache.spi.access.EntityDataAccess) StatisticsImplementor(org.hibernate.stat.spi.StatisticsImplementor) TypeHelper(org.hibernate.type.TypeHelper) Serializable(java.io.Serializable) EntityUpdateAction(org.hibernate.action.internal.EntityUpdateAction) CompletionStage(java.util.concurrent.CompletionStage) ReactiveEntityPersister(org.hibernate.reactive.persister.entity.impl.ReactiveEntityPersister) HibernateException(org.hibernate.HibernateException) CompletionStages.voidFuture(org.hibernate.reactive.util.impl.CompletionStages.voidFuture) Serializable(java.io.Serializable) AssertionFailure(org.hibernate.AssertionFailure) StatisticsImplementor(org.hibernate.stat.spi.StatisticsImplementor) CacheEntry(org.hibernate.cache.spi.entry.CacheEntry) ReactiveEntityPersister(org.hibernate.reactive.persister.entity.impl.ReactiveEntityPersister) EntityDataAccess(org.hibernate.cache.spi.access.EntityDataAccess)

Aggregations

ReactiveEntityPersister (org.hibernate.reactive.persister.entity.impl.ReactiveEntityPersister)15 Serializable (java.io.Serializable)11 EntityPersister (org.hibernate.persister.entity.EntityPersister)10 CompletionStage (java.util.concurrent.CompletionStage)8 HibernateException (org.hibernate.HibernateException)8 EntityDataAccess (org.hibernate.cache.spi.access.EntityDataAccess)8 PersistenceContext (org.hibernate.engine.spi.PersistenceContext)8 EntityKey (org.hibernate.engine.spi.EntityKey)6 SharedSessionContractImplementor (org.hibernate.engine.spi.SharedSessionContractImplementor)6 CompletionStages.completedFuture (org.hibernate.reactive.util.impl.CompletionStages.completedFuture)6 MethodHandles (java.lang.invoke.MethodHandles)5 LockMode (org.hibernate.LockMode)5 Log (org.hibernate.reactive.logging.impl.Log)5 LoggerFactory (org.hibernate.reactive.logging.impl.LoggerFactory)5 LockOptions (org.hibernate.LockOptions)4 StatisticsImplementor (org.hibernate.stat.spi.StatisticsImplementor)4 List (java.util.List)3 CompletableFuture (java.util.concurrent.CompletableFuture)3 EntityGraph (javax.persistence.EntityGraph)3 Tuple (javax.persistence.Tuple)3