Search in sources :

Example 1 with ReactiveEntityPersister

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

the class ReactiveEntityDeleteAction 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 = preDelete();
    Object version = getVersion();
    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
        version = persister.getVersion(instance);
    }
    final Object ck;
    if (persister.canWriteToCache()) {
        final EntityDataAccess cache = persister.getCacheAccessStrategy();
        ck = cache.generateCacheKey(id, persister, session.getFactory(), session.getTenantIdentifier());
        setLock(cache.lockItem(session, ck, version));
    } else {
        ck = null;
    }
    CompletionStage<Void> deleteStep = !isCascadeDeleteEnabled() && !veto ? ((ReactiveEntityPersister) persister).deleteReactive(id, version, instance, session) : voidFuture();
    return deleteStep.thenAccept(v -> {
        // postDelete:
        // After actually deleting a row, record the fact that the instance no longer
        // exists on the database (needed for identity-column key generation), and
        // remove it from the session cache
        final PersistenceContext persistenceContext = session.getPersistenceContextInternal();
        final EntityEntry entry = persistenceContext.removeEntry(instance);
        if (entry == null) {
            throw new AssertionFailure("possible non-threadsafe access to session");
        }
        entry.postDelete();
        persistenceContext.removeEntity(entry.getEntityKey());
        persistenceContext.removeProxy(entry.getEntityKey());
        if (persister.canWriteToCache()) {
            persister.getCacheAccessStrategy().remove(session, ck);
        }
        persistenceContext.getNaturalIdHelper().removeSharedNaturalIdCrossReference(persister, id, getNaturalIdValues());
        postDelete();
        final StatisticsImplementor statistics = getSession().getFactory().getStatistics();
        if (statistics.isStatisticsEnabled() && !veto) {
            statistics.deleteEntity(getPersister().getEntityName());
        }
    });
}
Also used : EntityPersister(org.hibernate.persister.entity.EntityPersister) ReactiveEntityPersister(org.hibernate.reactive.persister.entity.impl.ReactiveEntityPersister) Serializable(java.io.Serializable) EntityEntry(org.hibernate.engine.spi.EntityEntry) AssertionFailure(org.hibernate.AssertionFailure) SharedSessionContractImplementor(org.hibernate.engine.spi.SharedSessionContractImplementor) PersistenceContext(org.hibernate.engine.spi.PersistenceContext) StatisticsImplementor(org.hibernate.stat.spi.StatisticsImplementor) EntityDataAccess(org.hibernate.cache.spi.access.EntityDataAccess)

Example 2 with ReactiveEntityPersister

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

the class DefaultReactiveLoadEventListener method reactiveOnLoad.

/**
 * Handle the given load event.
 *
 * @param event The load event to be handled.
 */
@Override
public CompletionStage<Void> reactiveOnLoad(final LoadEvent event, final LoadEventListener.LoadType loadType) throws HibernateException {
    final ReactiveEntityPersister persister = (ReactiveEntityPersister) getPersister(event);
    if (persister == null) {
        throw LOG.unableToLocatePersister(event.getEntityClassName());
    }
    CompletionStage<Void> result = checkId(event, loadType, persister).thenCompose(vd -> doOnLoad(persister, event, loadType).thenAccept(event::setResult).handle((v, x) -> {
        if (event.getResult() instanceof CompletionStage) {
            throw new AssertionFailure("Unexpected CompletionStage");
        }
        if (x instanceof HibernateException) {
            LOG.unableToLoadCommand((HibernateException) x);
        }
        return returnNullorRethrow(x);
    }));
    // to go back to the database immediately and update the row
    if (event.getLockMode() == LockMode.PESSIMISTIC_FORCE_INCREMENT || event.getLockMode() == LockMode.FORCE) {
        // TODO: should we call CachedDomainDataAccess.lockItem() ?
        return result.thenCompose(v -> persister.lockReactive(event.getEntityId(), persister.getVersion(event.getResult()), event.getResult(), event.getLockOptions(), event.getSession()));
    } else {
        return result;
    }
}
Also used : TypeMismatchException(org.hibernate.TypeMismatchException) CacheEntityLoaderHelper(org.hibernate.loader.entity.CacheEntityLoaderHelper) ReactiveLoadEventListener(org.hibernate.reactive.event.ReactiveLoadEventListener) CompletionStages.completedFuture(org.hibernate.reactive.util.impl.CompletionStages.completedFuture) AssertionFailure(org.hibernate.AssertionFailure) EntityPersister(org.hibernate.persister.entity.EntityPersister) SessionUtil.checkEntityFound(org.hibernate.reactive.session.impl.SessionUtil.checkEntityFound) IdentifierProperty(org.hibernate.tuple.IdentifierProperty) EventSource(org.hibernate.event.spi.EventSource) EntityDataAccess(org.hibernate.cache.spi.access.EntityDataAccess) Log(org.hibernate.reactive.logging.impl.Log) EmbeddedComponentType(org.hibernate.type.EmbeddedComponentType) EntityType(org.hibernate.type.EntityType) CompletionStages.returnNullorRethrow(org.hibernate.reactive.util.impl.CompletionStages.returnNullorRethrow) PersistenceContext(org.hibernate.engine.spi.PersistenceContext) LoggerFactory(org.hibernate.reactive.logging.impl.LoggerFactory) HibernateProxy(org.hibernate.proxy.HibernateProxy) NonUniqueObjectException(org.hibernate.NonUniqueObjectException) Status(org.hibernate.engine.spi.Status) CompletionStages.voidFuture(org.hibernate.reactive.util.impl.CompletionStages.voidFuture) SessionFactoryImplementor(org.hibernate.engine.spi.SessionFactoryImplementor) LockMode(org.hibernate.LockMode) DelayedPostInsertIdentifier(org.hibernate.action.internal.DelayedPostInsertIdentifier) LazyInitializer(org.hibernate.proxy.LazyInitializer) MethodHandles(java.lang.invoke.MethodHandles) StatisticsImplementor(org.hibernate.stat.spi.StatisticsImplementor) EntityKey(org.hibernate.engine.spi.EntityKey) EntityMetamodel(org.hibernate.tuple.entity.EntityMetamodel) Serializable(java.io.Serializable) LoadEventListener(org.hibernate.event.spi.LoadEventListener) MessageHelper.infoString(org.hibernate.pretty.MessageHelper.infoString) PersistentObjectException(org.hibernate.PersistentObjectException) SoftLock(org.hibernate.cache.spi.access.SoftLock) CompletionStages.nullFuture(org.hibernate.reactive.util.impl.CompletionStages.nullFuture) CompletionStage(java.util.concurrent.CompletionStage) EntityEntry(org.hibernate.engine.spi.EntityEntry) SessionImplementor(org.hibernate.engine.spi.SessionImplementor) ReactiveEntityPersister(org.hibernate.reactive.persister.entity.impl.ReactiveEntityPersister) HibernateException(org.hibernate.HibernateException) Type(org.hibernate.type.Type) LoadEvent(org.hibernate.event.spi.LoadEvent) SessionUtil.throwEntityNotFound(org.hibernate.reactive.session.impl.SessionUtil.throwEntityNotFound) AssertionFailure(org.hibernate.AssertionFailure) ReactiveEntityPersister(org.hibernate.reactive.persister.entity.impl.ReactiveEntityPersister) HibernateException(org.hibernate.HibernateException) CompletionStage(java.util.concurrent.CompletionStage)

Example 3 with ReactiveEntityPersister

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

the class ReactiveEntityIdentityInsertAction method reactiveExecute.

@Override
public CompletionStage<Void> reactiveExecute() throws HibernateException {
    CompletionStage<Void> stage = reactiveNullifyTransientReferencesIfNotAlready();
    final EntityPersister persister = getPersister();
    final SharedSessionContractImplementor session = getSession();
    final Object instance = getInstance();
    setVeto(preInsert());
    if (!isVeto()) {
        ReactiveEntityPersister reactivePersister = (ReactiveEntityPersister) persister;
        return stage.thenCompose(v -> reactivePersister.insertReactive(getState(), instance, session)).thenApply(this::applyGeneratedId).thenCompose(generatedId -> processInsertGenerated(reactivePersister, generatedId, instance, session).thenApply(v -> generatedId)).thenAccept(generatedId -> {
            // need to do that here rather than in the save event listener to let
            // the post insert events to have a id-filled entity when IDENTITY is used (EJB3)
            persister.setIdentifier(instance, generatedId, session);
            final PersistenceContext persistenceContext = session.getPersistenceContextInternal();
            persistenceContext.registerInsertedKey(getPersister(), generatedId);
            EntityKey entityKey = session.generateEntityKey(generatedId, persister);
            setEntityKey(entityKey);
            persistenceContext.checkUniqueness(entityKey, getInstance());
            postInsert();
            final StatisticsImplementor statistics = session.getFactory().getStatistics();
            if (statistics.isStatisticsEnabled() && !isVeto()) {
                statistics.insertEntity(getPersister().getEntityName());
            }
            markExecuted();
        });
    } else {
        postInsert();
        markExecuted();
        return stage;
    }
}
Also used : EntityPersister(org.hibernate.persister.entity.EntityPersister) ReactiveEntityPersister(org.hibernate.reactive.persister.entity.impl.ReactiveEntityPersister) CompletionStage(java.util.concurrent.CompletionStage) EntityPersister(org.hibernate.persister.entity.EntityPersister) EntityIdentityInsertAction(org.hibernate.action.internal.EntityIdentityInsertAction) StatisticsImplementor(org.hibernate.stat.spi.StatisticsImplementor) EntityKey(org.hibernate.engine.spi.EntityKey) ReactiveEntityPersister(org.hibernate.reactive.persister.entity.impl.ReactiveEntityPersister) HibernateException(org.hibernate.HibernateException) PersistenceContext(org.hibernate.engine.spi.PersistenceContext) CompletionStages.voidFuture(org.hibernate.reactive.util.impl.CompletionStages.voidFuture) Serializable(java.io.Serializable) SharedSessionContractImplementor(org.hibernate.engine.spi.SharedSessionContractImplementor) EntityKey(org.hibernate.engine.spi.EntityKey) ReactiveEntityPersister(org.hibernate.reactive.persister.entity.impl.ReactiveEntityPersister) SharedSessionContractImplementor(org.hibernate.engine.spi.SharedSessionContractImplementor) PersistenceContext(org.hibernate.engine.spi.PersistenceContext) StatisticsImplementor(org.hibernate.stat.spi.StatisticsImplementor)

Example 4 with ReactiveEntityPersister

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

the class ReactiveEntityRegularInsertAction method reactiveExecute.

@Override
public CompletionStage<Void> reactiveExecute() throws HibernateException {
    return reactiveNullifyTransientReferencesIfNotAlready().thenCompose(v -> {
        EntityPersister persister = getPersister();
        final SharedSessionContractImplementor session = getSession();
        final Object instance = getInstance();
        final Serializable id = getId();
        // FIXME: It needs to become async
        final boolean veto = preInsert();
        // Don't need to lock the cache here, since if someone
        // else inserted the same pk first, the insert would fail
        CompletionStage<Void> insertStage;
        if (!veto) {
            ReactiveEntityPersister reactivePersister = (ReactiveEntityPersister) persister;
            insertStage = reactivePersister.insertReactive(id, getState(), instance, session).thenApply(res -> {
                EntityEntry entry = session.getPersistenceContext().getEntry(instance);
                if (entry == null) {
                    throw new AssertionFailure("possible non-threadsafe access to session");
                }
                entry.postInsert(getState());
                return entry;
            }).thenCompose(entry -> processInsertGeneratedProperties(reactivePersister, session, instance, id, entry).thenAccept(vv -> session.getPersistenceContext().registerInsertedKey(persister, getId())));
        } else {
            insertStage = voidFuture();
        }
        return insertStage.thenApply(res -> {
            final SessionFactoryImplementor factory = session.getFactory();
            if (isCachePutEnabled(persister, session)) {
                final CacheEntry ce = persister.buildCacheEntry(instance, getState(), getVersion(), session);
                setCacheEntry(persister.getCacheEntryStructure().structure(ce));
                final EntityDataAccess cache = persister.getCacheAccessStrategy();
                final Object ck = cache.generateCacheKey(id, persister, factory, session.getTenantIdentifier());
                final boolean put = cacheInsert(persister, ck);
                if (put && factory.getStatistics().isStatisticsEnabled()) {
                    factory.getStatistics().entityCachePut(persister.getNavigableRole(), persister.getCacheAccessStrategy().getRegion().getName());
                }
            }
            handleNaturalIdPostSaveNotifications(id);
            postInsert();
            if (factory.getStatistics().isStatisticsEnabled() && !veto) {
                factory.getStatistics().insertEntity(getEntityName());
            }
            markExecuted();
            return null;
        });
    });
}
Also used : EntityPersister(org.hibernate.persister.entity.EntityPersister) ReactiveEntityPersister(org.hibernate.reactive.persister.entity.impl.ReactiveEntityPersister) CacheEntry(org.hibernate.cache.spi.entry.CacheEntry) AssertionFailure(org.hibernate.AssertionFailure) EntityPersister(org.hibernate.persister.entity.EntityPersister) EntityDataAccess(org.hibernate.cache.spi.access.EntityDataAccess) EntityKey(org.hibernate.engine.spi.EntityKey) Serializable(java.io.Serializable) CompletionStage(java.util.concurrent.CompletionStage) EntityEntry(org.hibernate.engine.spi.EntityEntry) ReactiveEntityPersister(org.hibernate.reactive.persister.entity.impl.ReactiveEntityPersister) HibernateException(org.hibernate.HibernateException) CompletionStages.voidFuture(org.hibernate.reactive.util.impl.CompletionStages.voidFuture) SessionFactoryImplementor(org.hibernate.engine.spi.SessionFactoryImplementor) EntityInsertAction(org.hibernate.action.internal.EntityInsertAction) SharedSessionContractImplementor(org.hibernate.engine.spi.SharedSessionContractImplementor) Serializable(java.io.Serializable) AssertionFailure(org.hibernate.AssertionFailure) SessionFactoryImplementor(org.hibernate.engine.spi.SessionFactoryImplementor) SharedSessionContractImplementor(org.hibernate.engine.spi.SharedSessionContractImplementor) CacheEntry(org.hibernate.cache.spi.entry.CacheEntry) EntityEntry(org.hibernate.engine.spi.EntityEntry) ReactiveEntityPersister(org.hibernate.reactive.persister.entity.impl.ReactiveEntityPersister) EntityDataAccess(org.hibernate.cache.spi.access.EntityDataAccess)

Example 5 with ReactiveEntityPersister

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

the class DefaultReactiveResolveNaturalIdEventListener method loadFromDatasource.

/**
 * Performs the process of loading an entity from the configured
 * underlying datasource.
 *
 * @param event The load event
 *
 * @return The object loaded from the datasource, or null if not found.
 */
protected CompletionStage<Serializable> loadFromDatasource(ResolveNaturalIdEvent event) {
    EventSource session = event.getSession();
    StatisticsImplementor statistics = session.getFactory().getStatistics();
    boolean statisticsEnabled = statistics.isStatisticsEnabled();
    long startTime = statisticsEnabled ? System.nanoTime() : 0;
    EntityPersister entityPersister = event.getEntityPersister();
    Object[] orderedNaturalIdValues = event.getOrderedNaturalIdValues();
    return ((ReactiveEntityPersister) entityPersister).reactiveLoadEntityIdByNaturalId(orderedNaturalIdValues, event.getLockOptions(), session).thenApply(pk -> {
        if (statisticsEnabled) {
            statistics.naturalIdQueryExecuted(entityPersister.getRootEntityName(), MILLISECONDS.convert(System.nanoTime() - startTime, NANOSECONDS));
        }
        // PK can be null if the entity doesn't exist
        if (pk != null) {
            getNaturalIdHelper(event).cacheNaturalIdCrossReferenceFromLoad(entityPersister, pk, orderedNaturalIdValues);
        }
        return pk;
    });
}
Also used : EntityPersister(org.hibernate.persister.entity.EntityPersister) ReactiveEntityPersister(org.hibernate.reactive.persister.entity.impl.ReactiveEntityPersister) EventSource(org.hibernate.event.spi.EventSource) StatisticsImplementor(org.hibernate.stat.spi.StatisticsImplementor)

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