From a418ce8685cb54a5839971d6ed2cba2ece2f30f4 Mon Sep 17 00:00:00 2001 From: Davide D'Alto Date: Fri, 1 Sep 2023 10:12:14 +0200 Subject: [PATCH 1/6] [#1744] Upgrade Hibernate ORM to 6.2.8.Final --- build.gradle | 2 +- .../ReactiveEntityRegularInsertAction.java | 26 ----- .../impl/ReactiveEntityUpdateAction.java | 77 +------------ .../internal/ReactiveMutationExecutor.java | 3 +- .../ReactiveMutationExecutorPostInsert.java | 51 +++++---- ...MutationExecutorPostInsertSingleTable.java | 23 +--- ...ReactiveMutationExecutorSingleBatched.java | 9 +- .../ReactiveMutationExecutorStandard.java | 3 +- ...ReactiveAbstractCollectionBatchLoader.java | 3 +- ...activeCollectionBatchLoaderArrayParam.java | 5 +- ...ctiveCollectionBatchLoaderInPredicate.java | 11 +- .../ReactiveEntityBatchLoaderArrayParam.java | 5 +- .../ReactiveEntityBatchLoaderInPredicate.java | 9 +- ...ReactiveMultiIdEntityLoaderArrayParam.java | 4 +- .../ReactiveBasicCollectionPersister.java | 9 +- .../impl/ReactiveOneToManyPersister.java | 9 +- ...ReactiveDeleteRowsCoordinatorStandard.java | 3 +- ...ReactiveInsertRowsCoordinatorStandard.java | 3 +- .../ReactiveRemoveCoordinatorStandard.java | 6 +- .../session/impl/ReactiveSessionImpl.java | 107 ------------------ .../impl/ReactiveStatelessSessionImpl.java | 97 ---------------- .../ReactiveAbstractEntityInitializer.java | 6 +- .../ReactiveEntitySelectFetchInitializer.java | 12 +- .../internal/ReactiveResultsHelper.java | 2 +- 24 files changed, 74 insertions(+), 411 deletions(-) diff --git a/build.gradle b/build.gradle index 8d282f3ff..106189b8b 100644 --- a/build.gradle +++ b/build.gradle @@ -53,7 +53,7 @@ version = projectVersion // ./gradlew clean build -PhibernateOrmVersion=5.6.15-SNAPSHOT ext { if ( !project.hasProperty('hibernateOrmVersion') ) { - hibernateOrmVersion = '6.2.7.Final' + hibernateOrmVersion = '6.2.8.Final' } if ( !project.hasProperty( 'hibernateOrmGradlePluginVersion' ) ) { // Same as ORM as default diff --git a/hibernate-reactive-core/src/main/java/org/hibernate/reactive/engine/impl/ReactiveEntityRegularInsertAction.java b/hibernate-reactive-core/src/main/java/org/hibernate/reactive/engine/impl/ReactiveEntityRegularInsertAction.java index 0e2045521..9513ac231 100644 --- a/hibernate-reactive-core/src/main/java/org/hibernate/reactive/engine/impl/ReactiveEntityRegularInsertAction.java +++ b/hibernate-reactive-core/src/main/java/org/hibernate/reactive/engine/impl/ReactiveEntityRegularInsertAction.java @@ -11,17 +11,13 @@ import org.hibernate.HibernateException; import org.hibernate.action.internal.AbstractEntityInsertAction; import org.hibernate.action.internal.EntityInsertAction; -import org.hibernate.cache.spi.access.EntityDataAccess; -import org.hibernate.cache.spi.entry.CacheEntry; import org.hibernate.engine.spi.EntityEntry; import org.hibernate.engine.spi.EntityKey; import org.hibernate.engine.spi.PersistenceContext; -import org.hibernate.engine.spi.SessionFactoryImplementor; import org.hibernate.engine.spi.SharedSessionContractImplementor; import org.hibernate.event.spi.EventSource; import org.hibernate.persister.entity.EntityPersister; import org.hibernate.reactive.persister.entity.impl.ReactiveEntityPersister; -import org.hibernate.stat.internal.StatsHelper; import org.hibernate.stat.spi.StatisticsImplementor; import static org.hibernate.reactive.util.impl.CompletionStages.voidFuture; @@ -104,28 +100,6 @@ public CompletionStage reactiveExecute() throws HibernateException { } } - //TODO: copy/paste from superclass (make it protected) - private void putCacheIfNecessary() { - final EntityPersister persister = getPersister(); - final SharedSessionContractImplementor session = getSession(); - if ( isCachePutEnabled( persister, session ) ) { - final SessionFactoryImplementor factory = session.getFactory(); - final CacheEntry ce = persister.buildCacheEntry( getInstance(), getState(), getVersion(), session ); - setCacheEntry( persister.getCacheEntryStructure().structure( ce ) ); - final EntityDataAccess cache = persister.getCacheAccessStrategy(); - final Object ck = cache.generateCacheKey( getId(), persister, factory, session.getTenantIdentifier() ); - final boolean put = cacheInsert( persister, ck ); - - final StatisticsImplementor statistics = factory.getStatistics(); - if ( put && statistics.isStatisticsEnabled() ) { - statistics.entityCachePut( - StatsHelper.INSTANCE.getRootEntityRole( persister ), - cache.getRegion().getName() - ); - } - } - } - private CompletionStage processInsertGeneratedProperties( ReactiveEntityPersister persister, SharedSessionContractImplementor session, diff --git a/hibernate-reactive-core/src/main/java/org/hibernate/reactive/engine/impl/ReactiveEntityUpdateAction.java b/hibernate-reactive-core/src/main/java/org/hibernate/reactive/engine/impl/ReactiveEntityUpdateAction.java index 9ef65faee..f9ac63fc3 100644 --- a/hibernate-reactive-core/src/main/java/org/hibernate/reactive/engine/impl/ReactiveEntityUpdateAction.java +++ b/hibernate-reactive-core/src/main/java/org/hibernate/reactive/engine/impl/ReactiveEntityUpdateAction.java @@ -8,21 +8,15 @@ import java.util.concurrent.CompletionStage; import org.hibernate.AssertionFailure; -import org.hibernate.CacheMode; import org.hibernate.HibernateException; import org.hibernate.action.internal.EntityUpdateAction; -import org.hibernate.cache.spi.access.EntityDataAccess; -import org.hibernate.cache.spi.entry.CacheEntry; -import org.hibernate.engine.spi.CachedNaturalIdValueSource; import org.hibernate.engine.spi.EntityEntry; import org.hibernate.engine.spi.SharedSessionContractImplementor; import org.hibernate.engine.spi.Status; import org.hibernate.event.spi.EventSource; -import org.hibernate.metamodel.mapping.NaturalIdMapping; import org.hibernate.persister.entity.EntityPersister; import org.hibernate.reactive.engine.ReactiveExecutable; import org.hibernate.reactive.persister.entity.impl.ReactiveEntityPersister; -import org.hibernate.stat.internal.StatsHelper; import org.hibernate.stat.spi.StatisticsImplementor; import org.hibernate.tuple.entity.EntityMetamodel; import org.hibernate.type.TypeHelper; @@ -156,82 +150,13 @@ private void handleDeleted(EntityEntry entry, EntityPersister persister, Object } } - // TODO: copy/paste from superclass (make it protected) - private void handleNaturalIdResolutions(EntityPersister persister, SharedSessionContractImplementor session, Object id) { - NaturalIdMapping naturalIdMapping = getNaturalIdMapping(); - if ( naturalIdMapping != null ) { - session.getPersistenceContextInternal().getNaturalIdResolutions().manageSharedResolution( - id, - naturalIdMapping.extractNaturalIdFromEntityState( getState() ), - getPreviousNaturalIdValues(), - persister, - CachedNaturalIdValueSource.UPDATE - ); - } - } - - // TODO: copy/paste from superclass (make it protected) - private void updateCacheItem(Object previousVersion, Object ck, EntityEntry entry) { - final EntityPersister persister = getPersister(); - if ( persister.canWriteToCache() ) { - final SharedSessionContractImplementor session = getSession(); - if ( isCacheInvalidationRequired( persister, session ) || 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( getInstance(), getState(), getNextVersion(), getSession() ); - setCacheEntry( persister.getCacheEntryStructure().structure( ce ) ); - final boolean put = updateCache( persister, previousVersion, ck ); - - final StatisticsImplementor statistics = session.getFactory().getStatistics(); - if ( put && statistics.isStatisticsEnabled() ) { - statistics.entityCachePut( - StatsHelper.INSTANCE.getRootEntityRole(persister), - getPersister().getCacheAccessStrategy().getRegion().getName() - ); - } - } - } - } - - private static boolean isCacheInvalidationRequired( - EntityPersister persister, - SharedSessionContractImplementor session) { - // the cache has to be invalidated when CacheMode is equal to GET or IGNORE - return persister.isCacheInvalidationRequired() - || session.getCacheMode() == CacheMode.GET - || session.getCacheMode() == CacheMode.IGNORE; - } - - // TODO: copy/paste from superclass (make it protected) - private Object lockCacheItem(Object previousVersion) { - final EntityPersister persister = getPersister(); - if ( persister.canWriteToCache() ) { - final SharedSessionContractImplementor session = getSession(); - final EntityDataAccess cache = persister.getCacheAccessStrategy(); - final Object ck = cache.generateCacheKey( - getId(), - persister, - session.getFactory(), - session.getTenantIdentifier() - ); - setLock( cache.lockItem( session, ck, previousVersion ) ); - return ck; - } - else { - return null; - } - } - private CompletionStage processGeneratedProperties( Object id, ReactiveEntityPersister persister, SharedSessionContractImplementor session, Object instance) { if ( persister.hasUpdateGeneratedProperties() ) { - // this entity defines property generation, so process those generated - // values... + // this entity defines property generation, so process those generated values... if ( persister.isVersionPropertyGenerated() ) { throw new UnsupportedOperationException( "generated version attribute not supported in Hibernate Reactive" ); // setNextVersion( Versioning.getVersion( getState(), persister ) ); diff --git a/hibernate-reactive-core/src/main/java/org/hibernate/reactive/engine/jdbc/env/internal/ReactiveMutationExecutor.java b/hibernate-reactive-core/src/main/java/org/hibernate/reactive/engine/jdbc/env/internal/ReactiveMutationExecutor.java index 3027958f9..820fe582a 100644 --- a/hibernate-reactive-core/src/main/java/org/hibernate/reactive/engine/jdbc/env/internal/ReactiveMutationExecutor.java +++ b/hibernate-reactive-core/src/main/java/org/hibernate/reactive/engine/jdbc/env/internal/ReactiveMutationExecutor.java @@ -27,7 +27,6 @@ import static org.hibernate.reactive.engine.jdbc.ResultsCheckerUtil.checkResults; import static org.hibernate.reactive.util.impl.CompletionStages.voidFuture; import static org.hibernate.sql.model.ModelMutationLogging.MODEL_MUTATION_LOGGER; -import static org.hibernate.sql.model.ModelMutationLogging.MODEL_MUTATION_LOGGER_TRACE_ENABLED; /** * @see org.hibernate.engine.jdbc.mutation.internal.AbstractMutationExecutor @@ -95,7 +94,7 @@ default CompletionStage performReactiveNonBatchedMutation( final TableMapping tableDetails = statementDetails.getMutatingTableDetails(); if ( inclusionChecker != null && !inclusionChecker.include( tableDetails ) ) { - if ( MODEL_MUTATION_LOGGER_TRACE_ENABLED ) { + if ( MODEL_MUTATION_LOGGER.isTraceEnabled() ) { MODEL_MUTATION_LOGGER.tracef( "Skipping execution of secondary insert : %s", tableDetails.getTableName() ); } return voidFuture(); diff --git a/hibernate-reactive-core/src/main/java/org/hibernate/reactive/engine/jdbc/mutation/internal/ReactiveMutationExecutorPostInsert.java b/hibernate-reactive-core/src/main/java/org/hibernate/reactive/engine/jdbc/mutation/internal/ReactiveMutationExecutorPostInsert.java index 5b5f43bd7..f471e0b0c 100644 --- a/hibernate-reactive-core/src/main/java/org/hibernate/reactive/engine/jdbc/mutation/internal/ReactiveMutationExecutorPostInsert.java +++ b/hibernate-reactive-core/src/main/java/org/hibernate/reactive/engine/jdbc/mutation/internal/ReactiveMutationExecutorPostInsert.java @@ -5,12 +5,9 @@ */ package org.hibernate.reactive.engine.jdbc.mutation.internal; -import static org.hibernate.reactive.engine.jdbc.ResultsCheckerUtil.checkResults; -import static org.hibernate.reactive.util.impl.CompletionStages.completedFuture; -import static org.hibernate.sql.model.ModelMutationLogging.MODEL_MUTATION_LOGGER; -import static org.hibernate.sql.model.ModelMutationLogging.MODEL_MUTATION_LOGGER_TRACE_ENABLED; import java.util.concurrent.CompletionStage; import java.util.concurrent.atomic.AtomicReference; + import org.hibernate.engine.jdbc.mutation.OperationResultChecker; import org.hibernate.engine.jdbc.mutation.ParameterUsage; import org.hibernate.engine.jdbc.mutation.TableInclusionChecker; @@ -27,6 +24,10 @@ import org.hibernate.sql.model.MutationOperationGroup; import org.hibernate.sql.model.ValuesAnalysis; +import static org.hibernate.reactive.engine.jdbc.ResultsCheckerUtil.checkResults; +import static org.hibernate.reactive.util.impl.CompletionStages.completedFuture; +import static org.hibernate.sql.model.ModelMutationLogging.MODEL_MUTATION_LOGGER; + public class ReactiveMutationExecutorPostInsert extends MutationExecutorPostInsert implements ReactiveMutationExecutor { public ReactiveMutationExecutorPostInsert( @@ -53,17 +54,22 @@ public CompletionStage executeReactive(Object modelReference, ValuesAnal return completedFuture(id); } AtomicReference> res = new AtomicReference<>(completedFuture(id)); - secondaryTablesStatementGroup.forEachStatement((tableName, statementDetails) -> { - res.set(res.get().thenCompose(i -> reactiveExecuteWithId(i, tableName, statementDetails, inclusionChecker, resultChecker, session))); - }); + secondaryTablesStatementGroup + .forEachStatement( (tableName, statementDetails) -> res + .set( res.get().thenCompose( i -> reactiveExecuteWithId( i, tableName, statementDetails, inclusionChecker, resultChecker, session ) ) ) + ); return res.get(); }); } private Object logId(Object identifier) { - if ( MODEL_MUTATION_LOGGER_TRACE_ENABLED ) { + if ( MODEL_MUTATION_LOGGER.isTraceEnabled() ) { MODEL_MUTATION_LOGGER - .tracef( "Post-insert generated value : `%s` (%s)", identifier, mutationTarget.getNavigableRole().getFullPath() ); + .tracef( + "Post-insert generated value : `%s` (%s)", + identifier, + mutationTarget.getNavigableRole().getFullPath() + ); } return identifier; } @@ -77,33 +83,30 @@ private CompletionStage reactiveExecuteWithId( SharedSessionContractImplementor session) { if ( statementDetails == null ) { - return completedFuture(id); + return completedFuture( id ); } final EntityTableMapping tableDetails = (EntityTableMapping) statementDetails.getMutatingTableDetails(); assert !tableDetails.isIdentifierTable(); if ( inclusionChecker != null && !inclusionChecker.include( tableDetails ) ) { - if ( MODEL_MUTATION_LOGGER_TRACE_ENABLED ) { - MODEL_MUTATION_LOGGER.tracef( - "Skipping execution of secondary insert : %s", - tableDetails.getTableName() - ); + if ( MODEL_MUTATION_LOGGER.isTraceEnabled() ) { + MODEL_MUTATION_LOGGER + .tracef( "Skipping execution of secondary insert : %s", tableDetails.getTableName() ); } - return completedFuture(id); + return completedFuture( id ); } tableDetails.getKeyMapping().breakDownKeyJdbcValues( id, - (jdbcValue, columnMapping) -> { - valueBindings.bindValue( - jdbcValue, - tableName, - columnMapping.getColumnName(), - ParameterUsage.SET - ); - }, + (jdbcValue, columnMapping) -> valueBindings + .bindValue( + jdbcValue, + tableName, + columnMapping.getColumnName(), + ParameterUsage.SET + ), session ); diff --git a/hibernate-reactive-core/src/main/java/org/hibernate/reactive/engine/jdbc/mutation/internal/ReactiveMutationExecutorPostInsertSingleTable.java b/hibernate-reactive-core/src/main/java/org/hibernate/reactive/engine/jdbc/mutation/internal/ReactiveMutationExecutorPostInsertSingleTable.java index d18435a1c..2d14f3c96 100644 --- a/hibernate-reactive-core/src/main/java/org/hibernate/reactive/engine/jdbc/mutation/internal/ReactiveMutationExecutorPostInsertSingleTable.java +++ b/hibernate-reactive-core/src/main/java/org/hibernate/reactive/engine/jdbc/mutation/internal/ReactiveMutationExecutorPostInsertSingleTable.java @@ -5,7 +5,6 @@ */ package org.hibernate.reactive.engine.jdbc.mutation.internal; -import java.util.List; import java.util.concurrent.CompletionStage; import org.hibernate.engine.jdbc.mutation.OperationResultChecker; @@ -13,22 +12,15 @@ import org.hibernate.engine.jdbc.mutation.group.PreparedStatementDetails; import org.hibernate.engine.jdbc.mutation.internal.MutationExecutorPostInsertSingleTable; import org.hibernate.engine.spi.SharedSessionContractImplementor; -import org.hibernate.jdbc.Expectation; import org.hibernate.persister.entity.mutation.EntityMutationTarget; import org.hibernate.reactive.engine.jdbc.env.internal.ReactiveMutationExecutor; import org.hibernate.reactive.id.insert.ReactiveInsertGeneratedIdentifierDelegate; -import org.hibernate.sql.exec.spi.JdbcParameterBinder; import org.hibernate.sql.model.MutationOperationGroup; -import org.hibernate.sql.model.MutationTarget; import org.hibernate.sql.model.PreparableMutationOperation; -import org.hibernate.sql.model.TableMapping; import org.hibernate.sql.model.ValuesAnalysis; -import org.hibernate.sql.model.jdbc.JdbcInsertMutation; import static org.hibernate.engine.jdbc.mutation.internal.ModelMutationHelper.identityPreparation; import static org.hibernate.sql.model.ModelMutationLogging.MODEL_MUTATION_LOGGER; -import static org.hibernate.sql.model.ModelMutationLogging.MODEL_MUTATION_LOGGER_TRACE_ENABLED; - public class ReactiveMutationExecutorPostInsertSingleTable extends MutationExecutorPostInsertSingleTable implements ReactiveMutationExecutor { @@ -43,19 +35,6 @@ public ReactiveMutationExecutorPostInsertSingleTable(MutationOperationGroup muta this.identityInsertStatementDetails = identityPreparation( operation, session ); } - private static class ReactiveIdentityInsertMutation extends JdbcInsertMutation { - - public ReactiveIdentityInsertMutation( - TableMapping tableDetails, - MutationTarget mutationTarget, - String sql, - boolean callable, - Expectation expectation, - List parameterBinders) { - super( tableDetails, mutationTarget, sql, callable, expectation, parameterBinders ); - } - } - @Override public CompletionStage executeReactive( Object modelReference, @@ -74,7 +53,7 @@ public CompletionStage executeReactive( } private Object logId(Object identifier) { - if ( MODEL_MUTATION_LOGGER_TRACE_ENABLED ) { + if ( MODEL_MUTATION_LOGGER.isTraceEnabled() ) { MODEL_MUTATION_LOGGER .tracef( "Post-insert generated value : `%s` (%s)", identifier, mutationTarget.getNavigableRole().getFullPath() ); } diff --git a/hibernate-reactive-core/src/main/java/org/hibernate/reactive/engine/jdbc/mutation/internal/ReactiveMutationExecutorSingleBatched.java b/hibernate-reactive-core/src/main/java/org/hibernate/reactive/engine/jdbc/mutation/internal/ReactiveMutationExecutorSingleBatched.java index c7dce5ad4..13fdcb832 100644 --- a/hibernate-reactive-core/src/main/java/org/hibernate/reactive/engine/jdbc/mutation/internal/ReactiveMutationExecutorSingleBatched.java +++ b/hibernate-reactive-core/src/main/java/org/hibernate/reactive/engine/jdbc/mutation/internal/ReactiveMutationExecutorSingleBatched.java @@ -5,10 +5,8 @@ */ package org.hibernate.reactive.engine.jdbc.mutation.internal; -import static org.hibernate.reactive.util.impl.CompletionStages.voidFuture; -import static org.hibernate.sql.model.ModelMutationLogging.MODEL_MUTATION_LOGGER; -import static org.hibernate.sql.model.ModelMutationLogging.MODEL_MUTATION_LOGGER_TRACE_ENABLED; import java.util.concurrent.CompletionStage; + import org.hibernate.engine.jdbc.batch.spi.BatchKey; import org.hibernate.engine.jdbc.mutation.JdbcValueBindings; import org.hibernate.engine.jdbc.mutation.OperationResultChecker; @@ -26,6 +24,9 @@ import org.hibernate.sql.model.TableMapping; import org.hibernate.sql.model.ValuesAnalysis; +import static org.hibernate.reactive.util.impl.CompletionStages.voidFuture; +import static org.hibernate.sql.model.ModelMutationLogging.MODEL_MUTATION_LOGGER; + public class ReactiveMutationExecutorSingleBatched extends MutationExecutorSingleBatched implements ReactiveMutationExecutor { @@ -53,7 +54,7 @@ public CompletionStage performReactiveBatchedOperations( final TableMapping tableDetails = statementDetails.getMutatingTableDetails(); if ( inclusionChecker != null && !inclusionChecker.include( tableDetails ) ) { - if ( MODEL_MUTATION_LOGGER_TRACE_ENABLED ) { + if ( MODEL_MUTATION_LOGGER.isTraceEnabled() ) { MODEL_MUTATION_LOGGER.tracef( "Skipping execution of secondary insert : %s", tableDetails.getTableName() ); } return voidFuture(); diff --git a/hibernate-reactive-core/src/main/java/org/hibernate/reactive/engine/jdbc/mutation/internal/ReactiveMutationExecutorStandard.java b/hibernate-reactive-core/src/main/java/org/hibernate/reactive/engine/jdbc/mutation/internal/ReactiveMutationExecutorStandard.java index e3d75a005..3c274c214 100644 --- a/hibernate-reactive-core/src/main/java/org/hibernate/reactive/engine/jdbc/mutation/internal/ReactiveMutationExecutorStandard.java +++ b/hibernate-reactive-core/src/main/java/org/hibernate/reactive/engine/jdbc/mutation/internal/ReactiveMutationExecutorStandard.java @@ -29,7 +29,6 @@ import static org.hibernate.reactive.util.impl.CompletionStages.failedFuture; import static org.hibernate.reactive.util.impl.CompletionStages.voidFuture; import static org.hibernate.sql.model.ModelMutationLogging.MODEL_MUTATION_LOGGER; -import static org.hibernate.sql.model.ModelMutationLogging.MODEL_MUTATION_LOGGER_TRACE_ENABLED; /** * @see org.hibernate.engine.jdbc.mutation.internal.MutationExecutorStandard @@ -145,7 +144,7 @@ public CompletionStage performReactiveNonBatchedMutation( final TableMapping tableDetails = statementDetails.getMutatingTableDetails(); if ( inclusionChecker != null && !inclusionChecker.include( tableDetails ) ) { - if ( MODEL_MUTATION_LOGGER_TRACE_ENABLED ) { + if ( MODEL_MUTATION_LOGGER.isTraceEnabled() ) { MODEL_MUTATION_LOGGER .tracef( "Skipping execution of secondary insert : %s", tableDetails.getTableName() ); } diff --git a/hibernate-reactive-core/src/main/java/org/hibernate/reactive/loader/ast/internal/ReactiveAbstractCollectionBatchLoader.java b/hibernate-reactive-core/src/main/java/org/hibernate/reactive/loader/ast/internal/ReactiveAbstractCollectionBatchLoader.java index fc7cdb316..2dfd55dc6 100644 --- a/hibernate-reactive-core/src/main/java/org/hibernate/reactive/loader/ast/internal/ReactiveAbstractCollectionBatchLoader.java +++ b/hibernate-reactive-core/src/main/java/org/hibernate/reactive/loader/ast/internal/ReactiveAbstractCollectionBatchLoader.java @@ -17,7 +17,6 @@ import org.hibernate.reactive.loader.ast.spi.ReactiveCollectionBatchLoader; import org.hibernate.sql.results.internal.ResultsHelper; -import static org.hibernate.loader.ast.internal.MultiKeyLoadLogging.MULTI_KEY_LOAD_DEBUG_ENABLED; import static org.hibernate.loader.ast.internal.MultiKeyLoadLogging.MULTI_KEY_LOAD_LOGGER; /** @@ -73,7 +72,7 @@ protected void finishInitializingKey( return; } - if ( MULTI_KEY_LOAD_DEBUG_ENABLED ) { + if ( MULTI_KEY_LOAD_LOGGER.isDebugEnabled() ) { MULTI_KEY_LOAD_LOGGER.debugf( "Finishing initializing batch-fetched collection : %s.%s", attributeMapping.getNavigableRole().getFullPath(), key ); } diff --git a/hibernate-reactive-core/src/main/java/org/hibernate/reactive/loader/ast/internal/ReactiveCollectionBatchLoaderArrayParam.java b/hibernate-reactive-core/src/main/java/org/hibernate/reactive/loader/ast/internal/ReactiveCollectionBatchLoaderArrayParam.java index 4185d3646..efeafdd02 100644 --- a/hibernate-reactive-core/src/main/java/org/hibernate/reactive/loader/ast/internal/ReactiveCollectionBatchLoaderArrayParam.java +++ b/hibernate-reactive-core/src/main/java/org/hibernate/reactive/loader/ast/internal/ReactiveCollectionBatchLoaderArrayParam.java @@ -36,7 +36,6 @@ import org.hibernate.sql.results.internal.RowTransformerStandardImpl; import org.hibernate.type.BasicType; -import static org.hibernate.loader.ast.internal.MultiKeyLoadLogging.MULTI_KEY_LOAD_DEBUG_ENABLED; import static org.hibernate.loader.ast.internal.MultiKeyLoadLogging.MULTI_KEY_LOAD_LOGGER; /** @@ -58,7 +57,7 @@ public ReactiveCollectionBatchLoaderArrayParam( SessionFactoryImplementor sessionFactory) { super( domainBatchSize, loadQueryInfluencers, attributeMapping, sessionFactory ); - if ( MULTI_KEY_LOAD_DEBUG_ENABLED ) { + if ( MULTI_KEY_LOAD_LOGGER.isDebugEnabled() ) { MULTI_KEY_LOAD_LOGGER.debugf( "Using ARRAY batch fetching strategy for collection `%s` : %s", attributeMapping.getNavigableRole().getFullPath(), @@ -100,7 +99,7 @@ public ReactiveCollectionBatchLoaderArrayParam( @Override public CompletionStage> reactiveLoad(Object key, SharedSessionContractImplementor session) { - if ( MULTI_KEY_LOAD_DEBUG_ENABLED ) { + if ( MULTI_KEY_LOAD_LOGGER.isDebugEnabled() ) { MULTI_KEY_LOAD_LOGGER.debugf( "Batch loading entity `%s#%s`", getLoadable().getNavigableRole().getFullPath(), diff --git a/hibernate-reactive-core/src/main/java/org/hibernate/reactive/loader/ast/internal/ReactiveCollectionBatchLoaderInPredicate.java b/hibernate-reactive-core/src/main/java/org/hibernate/reactive/loader/ast/internal/ReactiveCollectionBatchLoaderInPredicate.java index 92a995620..230ba5ef4 100644 --- a/hibernate-reactive-core/src/main/java/org/hibernate/reactive/loader/ast/internal/ReactiveCollectionBatchLoaderInPredicate.java +++ b/hibernate-reactive-core/src/main/java/org/hibernate/reactive/loader/ast/internal/ReactiveCollectionBatchLoaderInPredicate.java @@ -26,7 +26,6 @@ import org.hibernate.sql.exec.spi.JdbcParameterBindings; import org.hibernate.sql.exec.spi.JdbcParametersList; -import static org.hibernate.loader.ast.internal.MultiKeyLoadLogging.MULTI_KEY_LOAD_DEBUG_ENABLED; import static org.hibernate.loader.ast.internal.MultiKeyLoadLogging.MULTI_KEY_LOAD_LOGGER; /** @@ -54,7 +53,7 @@ public ReactiveCollectionBatchLoaderInPredicate( .getDialect() .getBatchLoadSizingStrategy() .determineOptimalBatchLoadSize( keyColumnCount, domainBatchSize, false ); - if ( MULTI_KEY_LOAD_DEBUG_ENABLED ) { + if ( MULTI_KEY_LOAD_LOGGER.isDebugEnabled() ) { MULTI_KEY_LOAD_LOGGER.debugf( "Using IN-predicate batch fetching strategy for collection `%s` : %s (%s)", attributeMapping.getNavigableRole().getFullPath(), @@ -90,7 +89,7 @@ private static void doNothing(Object key1, int relativePosition, int absolutePos @Override public CompletionStage> reactiveLoad(Object key, SharedSessionContractImplementor session) { - if ( MULTI_KEY_LOAD_DEBUG_ENABLED ) { + if ( MULTI_KEY_LOAD_LOGGER.isDebugEnabled() ) { MULTI_KEY_LOAD_LOGGER.debugf( "Loading collection `%s#%s` by batch-fetch", getLoadable().getNavigableRole().getFullPath(), @@ -139,7 +138,7 @@ private CompletionStage initializeKeys( T[] keysToInitialize, int nonNullKeysToInitializeCount, SharedSessionContractImplementor session) { - if ( MULTI_KEY_LOAD_DEBUG_ENABLED ) { + if ( MULTI_KEY_LOAD_LOGGER.isDebugEnabled() ) { MULTI_KEY_LOAD_LOGGER.debugf( "Collection keys to batch-fetch initialize (`%s#%s`) %s", getLoadable().getNavigableRole().getFullPath(), @@ -175,7 +174,7 @@ private CompletionStage initializeKeys( }, ReactiveCollectionBatchLoaderInPredicate::doNothing, startIndex -> { - if ( MULTI_KEY_LOAD_DEBUG_ENABLED ) { + if ( MULTI_KEY_LOAD_LOGGER.isDebugEnabled() ) { MULTI_KEY_LOAD_LOGGER.debugf( "Processing collection batch-fetch chunk (`%s#%s`) %s - %s", getLoadable().getNavigableRole().getFullPath(), @@ -186,7 +185,7 @@ private CompletionStage initializeKeys( } }, (startIndex, nonNullElementCount) -> { - if ( MULTI_KEY_LOAD_DEBUG_ENABLED ) { + if ( MULTI_KEY_LOAD_LOGGER.isDebugEnabled() ) { MULTI_KEY_LOAD_LOGGER.debugf( "Finishing collection batch-fetch chunk (`%s#%s`) %s - %s (%s)", getLoadable().getNavigableRole().getFullPath(), diff --git a/hibernate-reactive-core/src/main/java/org/hibernate/reactive/loader/ast/internal/ReactiveEntityBatchLoaderArrayParam.java b/hibernate-reactive-core/src/main/java/org/hibernate/reactive/loader/ast/internal/ReactiveEntityBatchLoaderArrayParam.java index fab9a6eaa..fd38c813e 100644 --- a/hibernate-reactive-core/src/main/java/org/hibernate/reactive/loader/ast/internal/ReactiveEntityBatchLoaderArrayParam.java +++ b/hibernate-reactive-core/src/main/java/org/hibernate/reactive/loader/ast/internal/ReactiveEntityBatchLoaderArrayParam.java @@ -34,7 +34,6 @@ import org.hibernate.type.BasicType; import org.hibernate.type.BasicTypeRegistry; -import static org.hibernate.loader.ast.internal.MultiKeyLoadLogging.MULTI_KEY_LOAD_DEBUG_ENABLED; import static org.hibernate.loader.ast.internal.MultiKeyLoadLogging.MULTI_KEY_LOAD_LOGGER; /** @@ -58,7 +57,7 @@ public ReactiveEntityBatchLoaderArrayParam( super( entityDescriptor, sessionFactory ); this.domainBatchSize = domainBatchSize; - if ( MULTI_KEY_LOAD_DEBUG_ENABLED ) { + if ( MULTI_KEY_LOAD_LOGGER.isDebugEnabled() ) { MULTI_KEY_LOAD_LOGGER.debugf( "Batch fetching enabled for `%s` (entity) using ARRAY strategy : %s", entityDescriptor.getEntityName(), @@ -84,7 +83,7 @@ public final CompletionStage load( LockOptions lockOptions, Boolean readOnly, SharedSessionContractImplementor session) { - if ( MULTI_KEY_LOAD_DEBUG_ENABLED ) { + if ( MULTI_KEY_LOAD_LOGGER.isDebugEnabled() ) { MULTI_KEY_LOAD_LOGGER.debugf( "Batch fetching entity `%s#%s`", getLoadable().getEntityName(), pkValue ); } diff --git a/hibernate-reactive-core/src/main/java/org/hibernate/reactive/loader/ast/internal/ReactiveEntityBatchLoaderInPredicate.java b/hibernate-reactive-core/src/main/java/org/hibernate/reactive/loader/ast/internal/ReactiveEntityBatchLoaderInPredicate.java index 0a403a174..47a340233 100644 --- a/hibernate-reactive-core/src/main/java/org/hibernate/reactive/loader/ast/internal/ReactiveEntityBatchLoaderInPredicate.java +++ b/hibernate-reactive-core/src/main/java/org/hibernate/reactive/loader/ast/internal/ReactiveEntityBatchLoaderInPredicate.java @@ -30,7 +30,6 @@ import org.hibernate.sql.exec.spi.JdbcParametersList; import static org.hibernate.internal.util.collections.CollectionHelper.arrayList; -import static org.hibernate.loader.ast.internal.MultiKeyLoadLogging.MULTI_KEY_LOAD_DEBUG_ENABLED; import static org.hibernate.loader.ast.internal.MultiKeyLoadLogging.MULTI_KEY_LOAD_LOGGER; /** @@ -59,7 +58,7 @@ public ReactiveEntityBatchLoaderInPredicate( this.domainBatchSize = domainBatchSize; this.sqlBatchSize = sqlBatchSize; - if ( MULTI_KEY_LOAD_DEBUG_ENABLED ) { + if ( MULTI_KEY_LOAD_LOGGER.isDebugEnabled() ) { MULTI_KEY_LOAD_LOGGER.debugf( "Batch fetching `%s` entity using padded IN-list : %s (%s)", entityDescriptor.getEntityName(), @@ -86,12 +85,12 @@ public final CompletionStage load( LockOptions lockOptions, Boolean readOnly, SharedSessionContractImplementor session) { - if ( MULTI_KEY_LOAD_DEBUG_ENABLED ) { + if ( MULTI_KEY_LOAD_LOGGER.isDebugEnabled() ) { MULTI_KEY_LOAD_LOGGER.debugf( "Batch loading entity `%s#%s`", getLoadable().getEntityName(), pkValue ); } final Object[] idsToInitialize = resolveIdsToLoad( pkValue, session ); - if ( MULTI_KEY_LOAD_DEBUG_ENABLED ) { + if ( MULTI_KEY_LOAD_LOGGER.isDebugEnabled() ) { MULTI_KEY_LOAD_LOGGER.debugf( "Ids to batch-fetch initialize (`%s#%s`) %s", getLoadable().getEntityName(), @@ -161,7 +160,7 @@ protected CompletionStage initializeEntities( } }, (startIndex) -> { - if ( MULTI_KEY_LOAD_DEBUG_ENABLED ) { + if ( MULTI_KEY_LOAD_LOGGER.isDebugEnabled() ) { MULTI_KEY_LOAD_LOGGER.debugf( "Processing entity batch-fetch chunk (`%s#%s`) %s - %s", getLoadable().getEntityName(), diff --git a/hibernate-reactive-core/src/main/java/org/hibernate/reactive/loader/ast/internal/ReactiveMultiIdEntityLoaderArrayParam.java b/hibernate-reactive-core/src/main/java/org/hibernate/reactive/loader/ast/internal/ReactiveMultiIdEntityLoaderArrayParam.java index b37a780fd..04926a5e9 100644 --- a/hibernate-reactive-core/src/main/java/org/hibernate/reactive/loader/ast/internal/ReactiveMultiIdEntityLoaderArrayParam.java +++ b/hibernate-reactive-core/src/main/java/org/hibernate/reactive/loader/ast/internal/ReactiveMultiIdEntityLoaderArrayParam.java @@ -79,7 +79,7 @@ protected CompletionStage> performOrderedMultiLoad( K[] ids, MultiIdLoadOptions loadOptions, EventSource session) { - if ( MultiKeyLoadLogging.MULTI_KEY_LOAD_TRACE_ENABLED ) { + if ( MultiKeyLoadLogging.MULTI_KEY_LOAD_LOGGER.isTraceEnabled() ) { MultiKeyLoadLogging.MULTI_KEY_LOAD_LOGGER.tracef( "ReactiveMultiIdEntityLoaderArrayParam#performOrderedMultiLoad - %s", getLoadable().getEntityName() @@ -236,7 +236,7 @@ protected CompletionStage> performUnorderedMultiLoad( K[] ids, MultiIdLoadOptions loadOptions, EventSource session) { - if ( MultiKeyLoadLogging.MULTI_KEY_LOAD_TRACE_ENABLED ) { + if ( MultiKeyLoadLogging.MULTI_KEY_LOAD_LOGGER.isTraceEnabled() ) { MultiKeyLoadLogging.MULTI_KEY_LOAD_LOGGER.tracef( "ReactiveMultiIdEntityLoaderArrayParam#performUnorderedMultiLoad - %s", getLoadable().getEntityName() diff --git a/hibernate-reactive-core/src/main/java/org/hibernate/reactive/persister/collection/impl/ReactiveBasicCollectionPersister.java b/hibernate-reactive-core/src/main/java/org/hibernate/reactive/persister/collection/impl/ReactiveBasicCollectionPersister.java index 6dc170439..38dcaa921 100644 --- a/hibernate-reactive-core/src/main/java/org/hibernate/reactive/persister/collection/impl/ReactiveBasicCollectionPersister.java +++ b/hibernate-reactive-core/src/main/java/org/hibernate/reactive/persister/collection/impl/ReactiveBasicCollectionPersister.java @@ -36,7 +36,6 @@ import org.hibernate.reactive.util.impl.CompletionStages; import static org.hibernate.sql.model.ModelMutationLogging.MODEL_MUTATION_LOGGER; -import static org.hibernate.sql.model.ModelMutationLogging.MODEL_MUTATION_LOGGER_DEBUG_ENABLED; /** * A reactive {@link BasicCollectionPersister} @@ -82,7 +81,7 @@ private ReactiveUpdateRowsCoordinator buildUpdateRowCoordinator() { && !isInverse(); if ( !performUpdates ) { - if ( MODEL_MUTATION_LOGGER_DEBUG_ENABLED ) { + if ( MODEL_MUTATION_LOGGER.isDebugEnabled() ) { MODEL_MUTATION_LOGGER.debugf( "Skipping collection row updates - %s", getRolePath() ); } return new ReactiveUpdateRowsCoordinatorNoOp( this ); @@ -93,7 +92,7 @@ private ReactiveUpdateRowsCoordinator buildUpdateRowCoordinator() { private ReactiveInsertRowsCoordinator buildInsertRowCoordinator() { if ( isInverse() || !isRowInsertEnabled() ) { - if ( MODEL_MUTATION_LOGGER_DEBUG_ENABLED ) { + if ( MODEL_MUTATION_LOGGER.isDebugEnabled() ) { MODEL_MUTATION_LOGGER.debugf( "Skipping collection inserts - %s", getRolePath() ); } return new ReactiveInsertRowsCoordinatorNoOp( this ); @@ -104,7 +103,7 @@ private ReactiveInsertRowsCoordinator buildInsertRowCoordinator() { private ReactiveDeleteRowsCoordinator buildDeleteRowCoordinator() { if ( ! needsRemove() ) { - if ( MODEL_MUTATION_LOGGER_DEBUG_ENABLED ) { + if ( MODEL_MUTATION_LOGGER.isDebugEnabled() ) { MODEL_MUTATION_LOGGER.debugf( "Skipping collection row deletions - %s", getRolePath() ); } return new ReactiveDeleteRowsCoordinatorNoOp( this ); @@ -120,7 +119,7 @@ private ReactiveDeleteRowsCoordinator buildDeleteRowCoordinator() { private ReactiveRemoveCoordinator buildDeleteAllCoordinator() { if ( ! needsRemove() ) { - if ( MODEL_MUTATION_LOGGER_DEBUG_ENABLED ) { + if ( MODEL_MUTATION_LOGGER.isDebugEnabled() ) { MODEL_MUTATION_LOGGER.debugf( "Skipping collection removals - %s", getRolePath() ); } return new ReactiveRemoveCoordinatorNoOp( this ); diff --git a/hibernate-reactive-core/src/main/java/org/hibernate/reactive/persister/collection/impl/ReactiveOneToManyPersister.java b/hibernate-reactive-core/src/main/java/org/hibernate/reactive/persister/collection/impl/ReactiveOneToManyPersister.java index c713fd9d3..24ac87fb4 100644 --- a/hibernate-reactive-core/src/main/java/org/hibernate/reactive/persister/collection/impl/ReactiveOneToManyPersister.java +++ b/hibernate-reactive-core/src/main/java/org/hibernate/reactive/persister/collection/impl/ReactiveOneToManyPersister.java @@ -49,7 +49,6 @@ import static org.hibernate.reactive.util.impl.CompletionStages.loop; import static org.hibernate.reactive.util.impl.CompletionStages.voidFuture; import static org.hibernate.sql.model.ModelMutationLogging.MODEL_MUTATION_LOGGER; -import static org.hibernate.sql.model.ModelMutationLogging.MODEL_MUTATION_LOGGER_DEBUG_ENABLED; /** * A reactive {@link OneToManyPersister} @@ -98,7 +97,7 @@ public ReactiveRemoveCoordinator getRemoveCoordinator() { private ReactiveInsertRowsCoordinator buildInsertCoordinator() { if ( isInverse() || !isRowInsertEnabled() ) { - if ( MODEL_MUTATION_LOGGER_DEBUG_ENABLED ) { + if ( MODEL_MUTATION_LOGGER.isDebugEnabled() ) { MODEL_MUTATION_LOGGER.debugf( "Skipping collection (re)creation - %s", getRolePath() ); } return new ReactiveInsertRowsCoordinatorNoOp( this ); @@ -108,7 +107,7 @@ private ReactiveInsertRowsCoordinator buildInsertCoordinator() { private ReactiveUpdateRowsCoordinator buildUpdateCoordinator() { if ( !isRowDeleteEnabled() && !isRowInsertEnabled() ) { - if ( MODEL_MUTATION_LOGGER_DEBUG_ENABLED ) { + if ( MODEL_MUTATION_LOGGER.isDebugEnabled() ) { MODEL_MUTATION_LOGGER.debugf( "Skipping collection row updates - %s", getRolePath() ); } return new ReactiveUpdateRowsCoordinatorNoOp( this ); @@ -118,7 +117,7 @@ private ReactiveUpdateRowsCoordinator buildUpdateCoordinator() { private ReactiveDeleteRowsCoordinator buildDeleteCoordinator() { if ( !needsRemove() ) { - if ( MODEL_MUTATION_LOGGER_DEBUG_ENABLED ) { + if ( MODEL_MUTATION_LOGGER.isDebugEnabled() ) { MODEL_MUTATION_LOGGER.debugf( "Skipping collection row deletions - %s", getRolePath() ); } return new ReactiveDeleteRowsCoordinatorNoOp( this ); @@ -134,7 +133,7 @@ private ReactiveDeleteRowsCoordinator buildDeleteCoordinator() { private ReactiveRemoveCoordinator buildDeleteAllCoordinator() { if ( ! needsRemove() ) { - if ( MODEL_MUTATION_LOGGER_DEBUG_ENABLED ) { + if ( MODEL_MUTATION_LOGGER.isDebugEnabled() ) { MODEL_MUTATION_LOGGER.debugf( "Skipping collection removals - %s", getRolePath() ); } return new ReactiveRemoveCoordinatorNoOp( this ); diff --git a/hibernate-reactive-core/src/main/java/org/hibernate/reactive/persister/collection/mutation/ReactiveDeleteRowsCoordinatorStandard.java b/hibernate-reactive-core/src/main/java/org/hibernate/reactive/persister/collection/mutation/ReactiveDeleteRowsCoordinatorStandard.java index 770c775e1..f34add4a7 100644 --- a/hibernate-reactive-core/src/main/java/org/hibernate/reactive/persister/collection/mutation/ReactiveDeleteRowsCoordinatorStandard.java +++ b/hibernate-reactive-core/src/main/java/org/hibernate/reactive/persister/collection/mutation/ReactiveDeleteRowsCoordinatorStandard.java @@ -28,7 +28,6 @@ import static org.hibernate.reactive.util.impl.CompletionStages.loop; import static org.hibernate.reactive.util.impl.CompletionStages.voidFuture; import static org.hibernate.sql.model.ModelMutationLogging.MODEL_MUTATION_LOGGER; -import static org.hibernate.sql.model.ModelMutationLogging.MODEL_MUTATION_LOGGER_DEBUG_ENABLED; public class ReactiveDeleteRowsCoordinatorStandard extends DeleteRowsCoordinatorStandard implements ReactiveDeleteRowsCoordinator { private final RowMutationOperations rowMutationOperations; @@ -53,7 +52,7 @@ public CompletionStage reactiveDeleteRows(PersistentCollection collecti operationGroup = createOperationGroup(); } - if ( MODEL_MUTATION_LOGGER_DEBUG_ENABLED ) { + if ( MODEL_MUTATION_LOGGER.isDebugEnabled() ) { MODEL_MUTATION_LOGGER .debugf( "Deleting removed collection rows - %s : %s", getMutationTarget().getRolePath(), key ); } diff --git a/hibernate-reactive-core/src/main/java/org/hibernate/reactive/persister/collection/mutation/ReactiveInsertRowsCoordinatorStandard.java b/hibernate-reactive-core/src/main/java/org/hibernate/reactive/persister/collection/mutation/ReactiveInsertRowsCoordinatorStandard.java index 0f0bb29bb..2ea1d7593 100644 --- a/hibernate-reactive-core/src/main/java/org/hibernate/reactive/persister/collection/mutation/ReactiveInsertRowsCoordinatorStandard.java +++ b/hibernate-reactive-core/src/main/java/org/hibernate/reactive/persister/collection/mutation/ReactiveInsertRowsCoordinatorStandard.java @@ -30,7 +30,6 @@ import static org.hibernate.reactive.util.impl.CompletionStages.loop; import static org.hibernate.reactive.util.impl.CompletionStages.voidFuture; import static org.hibernate.sql.model.ModelMutationLogging.MODEL_MUTATION_LOGGER; -import static org.hibernate.sql.model.ModelMutationLogging.MODEL_MUTATION_LOGGER_DEBUG_ENABLED; /** * @see InsertRowsCoordinatorStandard @@ -71,7 +70,7 @@ public CompletionStage reactiveInsertRows(PersistentCollection collecti operationGroup = createOperationGroup(); } - if ( MODEL_MUTATION_LOGGER_DEBUG_ENABLED ) { + if ( MODEL_MUTATION_LOGGER.isDebugEnabled() ) { MODEL_MUTATION_LOGGER .debugf( "Inserting collection rows - %s : %s", mutationTarget.getRolePath(), id ); } diff --git a/hibernate-reactive-core/src/main/java/org/hibernate/reactive/persister/collection/mutation/ReactiveRemoveCoordinatorStandard.java b/hibernate-reactive-core/src/main/java/org/hibernate/reactive/persister/collection/mutation/ReactiveRemoveCoordinatorStandard.java index ec4ede1c9..3e1767399 100644 --- a/hibernate-reactive-core/src/main/java/org/hibernate/reactive/persister/collection/mutation/ReactiveRemoveCoordinatorStandard.java +++ b/hibernate-reactive-core/src/main/java/org/hibernate/reactive/persister/collection/mutation/ReactiveRemoveCoordinatorStandard.java @@ -30,8 +30,6 @@ import static org.hibernate.persister.collection.mutation.RowMutationOperations.DEFAULT_RESTRICTOR; import static org.hibernate.reactive.util.impl.CompletionStages.voidFuture; import static org.hibernate.sql.model.ModelMutationLogging.MODEL_MUTATION_LOGGER; -import static org.hibernate.sql.model.ModelMutationLogging.MODEL_MUTATION_LOGGER_DEBUG_ENABLED; -import static org.hibernate.sql.model.ModelMutationLogging.MODEL_MUTATION_LOGGER_TRACE_ENABLED; public class ReactiveRemoveCoordinatorStandard extends RemoveCoordinatorStandard implements ReactiveRemoveCoordinator { @@ -56,7 +54,7 @@ private BasicBatchKey getBatchKey() { @Override public CompletionStage reactiveDeleteAllRows(Object key, SharedSessionContractImplementor session) { - if ( MODEL_MUTATION_LOGGER_DEBUG_ENABLED ) { + if ( MODEL_MUTATION_LOGGER.isDebugEnabled() ) { MODEL_MUTATION_LOGGER .debugf( "Deleting collection - %s : %s", getMutationTarget().getRolePath(), key ); } @@ -98,7 +96,7 @@ protected MutationOperationGroupSingle buildOperationGroup() { assert getMutationTarget().getTargetPart() != null; assert getMutationTarget().getTargetPart().getKeyDescriptor() != null; - if ( MODEL_MUTATION_LOGGER_TRACE_ENABLED ) { + if ( MODEL_MUTATION_LOGGER.isTraceEnabled() ) { MODEL_MUTATION_LOGGER.tracef( "Starting RemoveCoordinator#buildOperationGroup - %s", getMutationTarget().getRolePath() ); } diff --git a/hibernate-reactive-core/src/main/java/org/hibernate/reactive/session/impl/ReactiveSessionImpl.java b/hibernate-reactive-core/src/main/java/org/hibernate/reactive/session/impl/ReactiveSessionImpl.java index fc03aa27e..02187c122 100644 --- a/hibernate-reactive-core/src/main/java/org/hibernate/reactive/session/impl/ReactiveSessionImpl.java +++ b/hibernate-reactive-core/src/main/java/org/hibernate/reactive/session/impl/ReactiveSessionImpl.java @@ -7,7 +7,6 @@ import java.lang.invoke.MethodHandles; import java.util.List; -import java.util.Locale; import java.util.Map; import java.util.Set; import java.util.concurrent.CompletionException; @@ -68,21 +67,13 @@ import org.hibernate.proxy.HibernateProxy; import org.hibernate.proxy.LazyInitializer; import org.hibernate.query.IllegalMutationQueryException; -import org.hibernate.query.IllegalNamedQueryOptionsException; -import org.hibernate.query.IllegalSelectQueryException; -import org.hibernate.query.QueryTypeMismatchException; import org.hibernate.query.criteria.JpaCriteriaInsertSelect; import org.hibernate.query.hql.spi.SqmQueryImplementor; import org.hibernate.query.named.NamedResultSetMappingMemento; import org.hibernate.query.spi.HqlInterpretation; -import org.hibernate.query.spi.QueryEngine; import org.hibernate.query.spi.QueryImplementor; -import org.hibernate.query.sql.spi.NamedNativeQueryMemento; import org.hibernate.query.sql.spi.NativeQueryImplementor; -import org.hibernate.query.sqm.internal.SqmSelectionQueryImpl; import org.hibernate.query.sqm.internal.SqmUtil; -import org.hibernate.query.sqm.spi.NamedSqmQueryMemento; -import org.hibernate.query.sqm.tree.SqmDmlStatement; import org.hibernate.query.sqm.tree.SqmStatement; import org.hibernate.query.sqm.tree.delete.SqmDeleteStatement; import org.hibernate.query.sqm.tree.insert.SqmInsertSelectStatement; @@ -135,9 +126,6 @@ import static org.hibernate.engine.internal.ManagedTypeHelper.isPersistentAttributeInterceptable; import static org.hibernate.engine.spi.NaturalIdResolutions.INVALID_NATURAL_ID_REFERENCE; import static org.hibernate.event.spi.LoadEventListener.IMMEDIATE_LOAD; -import static org.hibernate.event.spi.LoadEventListener.INTERNAL_LOAD_EAGER; -import static org.hibernate.event.spi.LoadEventListener.INTERNAL_LOAD_LAZY; -import static org.hibernate.event.spi.LoadEventListener.INTERNAL_LOAD_NULLABLE; import static org.hibernate.internal.util.StringHelper.isEmpty; import static org.hibernate.internal.util.StringHelper.isNotEmpty; import static org.hibernate.proxy.HibernateProxy.extractLazyInitializer; @@ -272,16 +260,6 @@ public CompletionStage reactiveInternalLoad(String entityName, Object id } ); } - //TODO: deleteme, use inherited version - private static LoadEventListener.LoadType internalLoadType(boolean eager, boolean nullable) { - if ( nullable ) { - return INTERNAL_LOAD_NULLABLE; - } - else { - return eager ? INTERNAL_LOAD_EAGER : INTERNAL_LOAD_LAZY; - } - } - @Override //Note: when making changes to this method, please also consider // the similar code in Mutiny.fetch() and Stage.fetch() @@ -400,16 +378,6 @@ public ReactiveQuery createReactiveQuery(String queryString, Class exp } } - private HqlInterpretation interpretHql(String hql, Class resultType) { - final QueryEngine queryEngine = getFactory().getQueryEngine(); - return queryEngine.getInterpretationCache() - .resolveHqlInterpretation( - hql, - resultType, - s -> queryEngine.getHqlTranslator().translate( hql, resultType ) - ); - } - @Override public ReactiveNativeQueryImplementor createReactiveNativeQuery(String sqlString) { checkOpen(); @@ -536,26 +504,6 @@ private ReactiveSelectionQuery createSelectionQuery(String hql, Class return query; } - private static void checkSelectionQuery(String hql, HqlInterpretation hqlInterpretation) { - if ( !( hqlInterpretation.getSqmStatement() instanceof SqmSelectStatement ) ) { - throw new IllegalSelectQueryException( "Expecting a selection query, but found `" + hql + "`", hql); - } - } - - private static void checkResultType(Class expectedResultType, SqmSelectionQueryImpl query) { - final Class resultType = query.getResultType(); - if ( !expectedResultType.isAssignableFrom( resultType ) ) { - throw new QueryTypeMismatchException( - String.format( - Locale.ROOT, - "Query result-type error - expecting `%s`, but found `%s`", - expectedResultType.getName(), - resultType.getName() - ) - ); - } - } - @Override public ReactiveQueryImplementor createReactiveNamedQuery(String name, Class resultType) { return (ReactiveQueryImplementor) buildNamedQuery( name, resultType ); @@ -575,13 +523,6 @@ public ReactiveMutationQuery createReactiveMutationQuery(String hqlString return new ReactiveQuerySqmImpl<>( sqmStatement, null, this ); } - // Change visibility in ORM - private static void checkMutationQuery(String hqlString, SqmStatement sqmStatement) { - if ( !( sqmStatement instanceof SqmDmlStatement ) ) { - throw new IllegalMutationQueryException( "Expecting a mutation query, but found `" + hqlString + "`" ); - } - } - @Override public ReactiveMutationQuery createReactiveMutationQuery(CriteriaUpdate updateQuery) { checkOpen(); @@ -624,44 +565,6 @@ public ReactiveMutationQuery createNamedReactiveMutationQuery(String quer ); } - // Copy and paste from ORM: change the visibility instead - private NativeQueryImplementor createNativeQueryImplementor(String queryName, NamedNativeQueryMemento memento) { - final NativeQueryImplementor query = memento.toQuery( this ); - final Boolean isUnequivocallySelect = query.isSelectQuery(); - if ( isUnequivocallySelect == TRUE ) { - throw new IllegalMutationQueryException( - "Expecting named native query (" + queryName + ") to be a mutation query, but found `" - + memento.getSqlString() + "`" - ); - } - if ( isEmpty( query.getComment() ) ) { - query.setComment( "dynamic native-SQL query" ); - } - applyQuerySettingsAndHints( query ); - return query; - } - - // Copy and paste from ORM: change the visibility instead - private SqmQueryImplementor createSqmQueryImplementor(String queryName, NamedSqmQueryMemento memento) { - final SqmQueryImplementor query = memento.toQuery( this ); - final SqmStatement sqmStatement = query.getSqmStatement(); - if ( !( sqmStatement instanceof SqmDmlStatement ) ) { - throw new IllegalMutationQueryException( - "Expecting a named mutation query (" + queryName + "), but found a select statement" - ); - } - if ( memento.getLockOptions() != null && ! memento.getLockOptions().isEmpty() ) { - throw new IllegalNamedQueryOptionsException( - "Named mutation query `" + queryName + "` specified lock-options" - ); - } - if ( isEmpty( query.getComment() ) ) { - query.setComment( "dynamic HQL query" ); - } - applyQuerySettingsAndHints( query ); - return query; - } - @Override public ReactiveSelectionQuery createNamedReactiveSelectionQuery(String queryName) { return (ReactiveSelectionQuery) createNamedSelectionQuery( queryName, null ); @@ -769,16 +672,6 @@ public Class getResultType() { }; } - //TODO: deleteme, call superclass method - private NamedResultSetMappingMemento getResultSetMappingMemento(String resultSetMappingName) { - final NamedResultSetMappingMemento resultSetMappingMemento = getFactory() - .getQueryEngine().getNamedObjectRepository().getResultSetMappingMemento( resultSetMappingName ); - if ( resultSetMappingMemento == null ) { - throw new HibernateException( "Could not resolve specified result-set mapping name: " + resultSetMappingName ); - } - return resultSetMappingMemento; - } - /** * @deprecated use {@link #reactiveInitializeCollection(PersistentCollection, boolean)} instead */ diff --git a/hibernate-reactive-core/src/main/java/org/hibernate/reactive/session/impl/ReactiveStatelessSessionImpl.java b/hibernate-reactive-core/src/main/java/org/hibernate/reactive/session/impl/ReactiveStatelessSessionImpl.java index 198fbd101..51cab378d 100644 --- a/hibernate-reactive-core/src/main/java/org/hibernate/reactive/session/impl/ReactiveStatelessSessionImpl.java +++ b/hibernate-reactive-core/src/main/java/org/hibernate/reactive/session/impl/ReactiveStatelessSessionImpl.java @@ -6,7 +6,6 @@ package org.hibernate.reactive.session.impl; import java.lang.invoke.MethodHandles; -import java.util.Locale; import java.util.concurrent.CompletableFuture; import java.util.concurrent.CompletionStage; @@ -40,22 +39,14 @@ import org.hibernate.proxy.HibernateProxy; import org.hibernate.proxy.LazyInitializer; import org.hibernate.query.IllegalMutationQueryException; -import org.hibernate.query.IllegalNamedQueryOptionsException; -import org.hibernate.query.IllegalSelectQueryException; -import org.hibernate.query.QueryTypeMismatchException; import org.hibernate.query.criteria.JpaCriteriaInsertSelect; import org.hibernate.query.hql.spi.SqmQueryImplementor; import org.hibernate.query.named.NamedResultSetMappingMemento; import org.hibernate.query.spi.HqlInterpretation; -import org.hibernate.query.spi.QueryEngine; import org.hibernate.query.spi.QueryImplementor; import org.hibernate.query.sql.internal.NativeQueryImpl; -import org.hibernate.query.sql.spi.NamedNativeQueryMemento; import org.hibernate.query.sql.spi.NativeQueryImplementor; -import org.hibernate.query.sqm.internal.SqmSelectionQueryImpl; import org.hibernate.query.sqm.internal.SqmUtil; -import org.hibernate.query.sqm.spi.NamedSqmQueryMemento; -import org.hibernate.query.sqm.tree.SqmDmlStatement; import org.hibernate.query.sqm.tree.SqmStatement; import org.hibernate.query.sqm.tree.delete.SqmDeleteStatement; import org.hibernate.query.sqm.tree.insert.SqmInsertSelectStatement; @@ -732,17 +723,6 @@ public ReactiveSqmQueryImplementor createReactiveQuery(String queryString } } - // TODO: copy and paste from ORM: change the visibility instead - private HqlInterpretation interpretHql(String hql, Class resultType) { - final QueryEngine queryEngine = getFactory().getQueryEngine(); - return queryEngine.getInterpretationCache() - .resolveHqlInterpretation( - hql, - resultType, - s -> queryEngine.getHqlTranslator().translate( hql, resultType ) - ); - } - @Override public ReactiveNativeQueryImplementor createReactiveNativeQuery(String sqlString) { checkOpen(); @@ -868,28 +848,6 @@ private ReactiveSelectionQuery createSelectionQuery(String hql, Class return query; } - // TODO: copy and paste from ORM: change the visibility instead - private static void checkSelectionQuery(String hql, HqlInterpretation hqlInterpretation) { - if ( !( hqlInterpretation.getSqmStatement() instanceof SqmSelectStatement ) ) { - throw new IllegalSelectQueryException( "Expecting a selection query, but found `" + hql + "`", hql); - } - } - - // TODO: copy and paste from ORM: change the visibility instead - private static void checkResultType(Class expectedResultType, SqmSelectionQueryImpl query) { - final Class resultType = query.getResultType(); - if ( !expectedResultType.isAssignableFrom( resultType ) ) { - throw new QueryTypeMismatchException( - String.format( - Locale.ROOT, - "Query result-type error - expecting `%s`, but found `%s`", - expectedResultType.getName(), - resultType.getName() - ) - ); - } - } - @Override public ReactiveSelectionQuery createReactiveSelectionQuery(CriteriaQuery criteria) { SqmUtil.verifyIsSelectStatement( (SqmStatement) criteria, null ); @@ -904,13 +862,6 @@ public ReactiveMutationQuery createReactiveMutationQuery(String hqlString return new ReactiveQuerySqmImpl<>( sqmStatement, null, this ); } - //TODO: change visibility in ORM - private static void checkMutationQuery(String hqlString, SqmStatement sqmStatement) { - if ( !( sqmStatement instanceof SqmDmlStatement ) ) { - throw new IllegalMutationQueryException( "Expecting a mutation query, but found `" + hqlString + "`" ); - } - } - @Override public ReactiveMutationQuery createReactiveMutationQuery(CriteriaUpdate updateQuery) { checkOpen(); @@ -958,44 +909,6 @@ public ReactiveMutationQuery createNamedReactiveMutationQuery(String quer ); } - // TODO: copy and paste from ORM: change the visibility instead - private NativeQueryImplementor createNativeQueryImplementor(String queryName, NamedNativeQueryMemento memento) { - final NativeQueryImplementor query = memento.toQuery( this ); - final Boolean isUnequivocallySelect = query.isSelectQuery(); - if ( isUnequivocallySelect == TRUE ) { - throw new IllegalMutationQueryException( - "Expecting named native query (" + queryName + ") to be a mutation query, but found `" - + memento.getSqlString() + "`" - ); - } - if ( isEmpty( query.getComment() ) ) { - query.setComment( "dynamic native-SQL query" ); - } - applyQuerySettingsAndHints( query ); - return query; - } - - // Copy and paste from ORM: change the visibility instead - private SqmQueryImplementor createSqmQueryImplementor(String queryName, NamedSqmQueryMemento memento) { - final SqmQueryImplementor query = memento.toQuery( this ); - final SqmStatement sqmStatement = query.getSqmStatement(); - if ( !( sqmStatement instanceof SqmDmlStatement ) ) { - throw new IllegalMutationQueryException( - "Expecting a named mutation query (" + queryName + "), but found a select statement" - ); - } - if ( memento.getLockOptions() != null && ! memento.getLockOptions().isEmpty() ) { - throw new IllegalNamedQueryOptionsException( - "Named mutation query `" + queryName + "` specified lock-options" - ); - } - if ( isEmpty( query.getComment() ) ) { - query.setComment( "dynamic HQL query" ); - } - applyQuerySettingsAndHints( query ); - return query; - } - @Override public ReactiveSelectionQuery createNamedReactiveSelectionQuery(String queryName, Class expectedResultType) { return (ReactiveSelectionQuery) createNamedSelectionQuery( queryName , expectedResultType ); @@ -1107,16 +1020,6 @@ private void addAffectedEntities(AffectedEntities affectedEntities, NativeQueryI } } - //TODO: deleteme, call superclass method - private NamedResultSetMappingMemento getResultSetMappingMemento(String resultSetMappingName) { - final NamedResultSetMappingMemento resultSetMappingMemento = getFactory() - .getQueryEngine().getNamedObjectRepository().getResultSetMappingMemento( resultSetMappingName ); - if ( resultSetMappingMemento == null ) { - throw new HibernateException( "Could not resolve specified result-set mapping name: " + resultSetMappingName ); - } - return resultSetMappingMemento; - } - @Override public void close() { throw LOG.nonReactiveMethodCall( "close(CompletableFuture closing)" ); diff --git a/hibernate-reactive-core/src/main/java/org/hibernate/reactive/sql/results/graph/entity/ReactiveAbstractEntityInitializer.java b/hibernate-reactive-core/src/main/java/org/hibernate/reactive/sql/results/graph/entity/ReactiveAbstractEntityInitializer.java index abbfa6e1f..389cee1f3 100644 --- a/hibernate-reactive-core/src/main/java/org/hibernate/reactive/sql/results/graph/entity/ReactiveAbstractEntityInitializer.java +++ b/hibernate-reactive-core/src/main/java/org/hibernate/reactive/sql/results/graph/entity/ReactiveAbstractEntityInitializer.java @@ -146,7 +146,7 @@ private Object resolveInstance( } else { // the entity is already being loaded elsewhere - if ( EntityLoadingLogging.DEBUG_ENABLED ) { + if ( EntityLoadingLogging.ENTITY_LOADING_LOGGER.isDebugEnabled() ) { EntityLoadingLogging.ENTITY_LOADING_LOGGER.debugf( "(%s) Entity [%s] being loaded by another initializer [%s] - skipping processing", getSimpleConcreteImplName(), @@ -189,7 +189,7 @@ private CompletionStage initializeEntityInstance(Object toInitialize, RowP final SharedSessionContractImplementor session = rowProcessingState.getSession(); final PersistenceContext persistenceContext = session.getPersistenceContextInternal(); - if ( EntityLoadingLogging.TRACE_ENABLED ) { + if ( EntityLoadingLogging.ENTITY_LOADING_LOGGER.isTraceEnabled() ) { EntityLoadingLogging.ENTITY_LOADING_LOGGER.tracef( "(%s) Beginning Initializer#initializeInstance process for entity %s", getSimpleConcreteImplName(), @@ -249,7 +249,7 @@ private CompletionStage initializeEntityInstance(Object toInitialize, RowP registerNaturalIdResolution( persistenceContext, entityIdentifier ); takeSnapshot( rowProcessingState, session, persistenceContext, entityEntry ); getConcreteDescriptor().afterInitialize( toInitialize, session ); - if ( EntityLoadingLogging.DEBUG_ENABLED ) { + if ( EntityLoadingLogging.ENTITY_LOADING_LOGGER.isDebugEnabled() ) { EntityLoadingLogging.ENTITY_LOADING_LOGGER.debugf( "(%s) Done materializing entityInstance : %s", getSimpleConcreteImplName(), diff --git a/hibernate-reactive-core/src/main/java/org/hibernate/reactive/sql/results/graph/entity/internal/ReactiveEntitySelectFetchInitializer.java b/hibernate-reactive-core/src/main/java/org/hibernate/reactive/sql/results/graph/entity/internal/ReactiveEntitySelectFetchInitializer.java index 119351b9f..45af27613 100644 --- a/hibernate-reactive-core/src/main/java/org/hibernate/reactive/sql/results/graph/entity/internal/ReactiveEntitySelectFetchInitializer.java +++ b/hibernate-reactive-core/src/main/java/org/hibernate/reactive/sql/results/graph/entity/internal/ReactiveEntitySelectFetchInitializer.java @@ -30,7 +30,6 @@ import org.hibernate.spi.NavigablePath; import org.hibernate.sql.results.graph.DomainResultAssembler; import org.hibernate.sql.results.graph.FetchParentAccess; -import org.hibernate.sql.results.graph.entity.EntityLoadingLogging; import org.hibernate.sql.results.graph.entity.LoadingEntityEntry; import org.hibernate.sql.results.graph.entity.internal.EntitySelectFetchInitializer; import org.hibernate.sql.results.jdbc.spi.RowProcessingState; @@ -41,7 +40,6 @@ import static org.hibernate.reactive.util.impl.CompletionStages.failedFuture; import static org.hibernate.reactive.util.impl.CompletionStages.voidFuture; import static org.hibernate.reactive.util.impl.CompletionStages.whileLoop; -import static org.hibernate.sql.results.graph.entity.EntityLoadingLogging.DEBUG_ENABLED; import static org.hibernate.sql.results.graph.entity.EntityLoadingLogging.ENTITY_LOADING_LOGGER; /** @@ -113,7 +111,7 @@ public CompletionStage reactiveInitializeInstance(ReactiveRowProcessingSta return voidFuture(); } - if ( EntityLoadingLogging.TRACE_ENABLED ) { + if ( ENTITY_LOADING_LOGGER.isTraceEnabled() ) { ENTITY_LOADING_LOGGER.tracef( "(%s) Beginning Initializer#resolveInstance process for entity (%s) : %s", StringHelper.collapse( this.getClass().getName() ), @@ -145,7 +143,7 @@ public CompletionStage reactiveInitializeInstance(ReactiveRowProcessingSta .findLoadingEntityEntry( entityKey ); if ( existingLoadingEntry != null ) { - if ( DEBUG_ENABLED ) { + if ( ENTITY_LOADING_LOGGER.isDebugEnabled() ) { ENTITY_LOADING_LOGGER.debugf( "(%s) Found existing loading entry [%s] - using loading instance", CONCRETE_NAME, @@ -156,7 +154,7 @@ public CompletionStage reactiveInitializeInstance(ReactiveRowProcessingSta if ( existingLoadingEntry.getEntityInitializer() != this ) { // the entity is already being loaded elsewhere - if ( DEBUG_ENABLED ) { + if ( ENTITY_LOADING_LOGGER.isDebugEnabled() ) { ENTITY_LOADING_LOGGER.debugf( "(%s) Entity [%s] being loaded by another initializer [%s] - skipping processing", CONCRETE_NAME, @@ -171,7 +169,7 @@ public CompletionStage reactiveInitializeInstance(ReactiveRowProcessingSta } } - if ( DEBUG_ENABLED ) { + if ( ENTITY_LOADING_LOGGER.isDebugEnabled() ) { ENTITY_LOADING_LOGGER.debugf( "(%s) Invoking session#internalLoad for entity (%s) : %s", CONCRETE_NAME, @@ -191,7 +189,7 @@ public CompletionStage reactiveInitializeInstance(ReactiveRowProcessingSta } } - if ( DEBUG_ENABLED ) { + if ( ENTITY_LOADING_LOGGER.isDebugEnabled() ) { ENTITY_LOADING_LOGGER.debugf( "(%s) Entity [%s] : %s has being loaded by session.internalLoad.", CONCRETE_NAME, diff --git a/hibernate-reactive-core/src/main/java/org/hibernate/reactive/sql/results/internal/ReactiveResultsHelper.java b/hibernate-reactive-core/src/main/java/org/hibernate/reactive/sql/results/internal/ReactiveResultsHelper.java index b1b6842ad..fca93e925 100644 --- a/hibernate-reactive-core/src/main/java/org/hibernate/reactive/sql/results/internal/ReactiveResultsHelper.java +++ b/hibernate-reactive-core/src/main/java/org/hibernate/reactive/sql/results/internal/ReactiveResultsHelper.java @@ -106,7 +106,7 @@ public SqlAstCreationContext getSqlAstCreationContext() { } private static void logInitializers(Map initializerMap) { - if ( ! ResultsLogger.DEBUG_ENABLED ) { + if ( ! ResultsLogger.RESULTS_MESSAGE_LOGGER.isDebugEnabled() ) { return; } From 9a7991eee739fad45b5fa1fc4ff5a234ca162ec7 Mon Sep 17 00:00:00 2001 From: Davide D'Alto Date: Fri, 25 Aug 2023 16:01:58 +0200 Subject: [PATCH 2/6] [#1744] Fix bug when updating with RowId Related to Hibernate ORM issue [HHH-17045](https://hibernate.atlassian.net/browse/HHH-17045): Unable to locate parameter for RESTRICT - UPDATE error when updating entity with RowId --- .../impl/PreparedStatementAdaptor.java | 2 +- .../adaptor/impl/ResultSetAdaptor.java | 24 +++++++++++++++++-- .../ReactiveEntityFetchJoinedImpl.java | 2 ++ .../ReactiveEntityJoinedFetchInitializer.java | 3 ++- 4 files changed, 27 insertions(+), 4 deletions(-) diff --git a/hibernate-reactive-core/src/main/java/org/hibernate/reactive/adaptor/impl/PreparedStatementAdaptor.java b/hibernate-reactive-core/src/main/java/org/hibernate/reactive/adaptor/impl/PreparedStatementAdaptor.java index 1bbea3436..9f44f03bd 100644 --- a/hibernate-reactive-core/src/main/java/org/hibernate/reactive/adaptor/impl/PreparedStatementAdaptor.java +++ b/hibernate-reactive-core/src/main/java/org/hibernate/reactive/adaptor/impl/PreparedStatementAdaptor.java @@ -275,7 +275,7 @@ public ParameterMetaData getParameterMetaData() { @Override public void setRowId(int parameterIndex, RowId x) { - throw new UnsupportedOperationException(); + put( parameterIndex, Buffer.buffer( x.getBytes() ) ); } @Override diff --git a/hibernate-reactive-core/src/main/java/org/hibernate/reactive/adaptor/impl/ResultSetAdaptor.java b/hibernate-reactive-core/src/main/java/org/hibernate/reactive/adaptor/impl/ResultSetAdaptor.java index b4295b5e6..24f3f5b9d 100644 --- a/hibernate-reactive-core/src/main/java/org/hibernate/reactive/adaptor/impl/ResultSetAdaptor.java +++ b/hibernate-reactive-core/src/main/java/org/hibernate/reactive/adaptor/impl/ResultSetAdaptor.java @@ -30,6 +30,7 @@ import java.util.Calendar; import java.util.Map; import java.util.NoSuchElementException; +import java.util.Objects; import java.util.function.Function; import org.hibernate.engine.jdbc.BlobProxy; @@ -847,12 +848,31 @@ public SQLXML getSQLXML(String columnLabel) { @Override public RowId getRowId(int columnIndex) { - throw new UnsupportedOperationException(); + Buffer buffer = row.getBuffer( columnIndex - 1 ); + wasNull = buffer == null; + return wasNull ? null : new RowIdAdaptor( buffer ); } @Override public RowId getRowId(String columnLabel) { - throw new UnsupportedOperationException(); + Buffer buffer = row.getBuffer( columnLabel ); + wasNull = buffer == null; + return wasNull ? null : new RowIdAdaptor( buffer ); + } + + private static class RowIdAdaptor implements RowId { + + private final Buffer buffer; + + private RowIdAdaptor(Buffer buffer) { + Objects.requireNonNull( buffer ); + this.buffer = buffer; + } + + @Override + public byte[] getBytes() { + return buffer.getBytes(); + } } @Override diff --git a/hibernate-reactive-core/src/main/java/org/hibernate/reactive/sql/results/graph/entity/internal/ReactiveEntityFetchJoinedImpl.java b/hibernate-reactive-core/src/main/java/org/hibernate/reactive/sql/results/graph/entity/internal/ReactiveEntityFetchJoinedImpl.java index fb1c67246..a5edf834a 100644 --- a/hibernate-reactive-core/src/main/java/org/hibernate/reactive/sql/results/graph/entity/internal/ReactiveEntityFetchJoinedImpl.java +++ b/hibernate-reactive-core/src/main/java/org/hibernate/reactive/sql/results/graph/entity/internal/ReactiveEntityFetchJoinedImpl.java @@ -29,6 +29,7 @@ protected Initializer buildEntityJoinedFetchInitializer( LockMode lockMode, NotFoundAction notFoundAction, DomainResult keyResult, + DomainResult rowIdResult, Fetch identifierFetch, Fetch discriminatorFetch, AssemblerCreationState creationState) { @@ -39,6 +40,7 @@ protected Initializer buildEntityJoinedFetchInitializer( lockMode, notFoundAction, keyResult, + rowIdResult, identifierFetch, discriminatorFetch, creationState diff --git a/hibernate-reactive-core/src/main/java/org/hibernate/reactive/sql/results/graph/entity/internal/ReactiveEntityJoinedFetchInitializer.java b/hibernate-reactive-core/src/main/java/org/hibernate/reactive/sql/results/graph/entity/internal/ReactiveEntityJoinedFetchInitializer.java index 0b4c9ce90..d2a75d9d6 100644 --- a/hibernate-reactive-core/src/main/java/org/hibernate/reactive/sql/results/graph/entity/internal/ReactiveEntityJoinedFetchInitializer.java +++ b/hibernate-reactive-core/src/main/java/org/hibernate/reactive/sql/results/graph/entity/internal/ReactiveEntityJoinedFetchInitializer.java @@ -46,6 +46,7 @@ public ReactiveEntityJoinedFetchInitializer( LockMode lockMode, NotFoundAction notFoundAction, DomainResult keyResult, + DomainResult rowIdResult, Fetch identifierFetch, Fetch discriminatorFetch, AssemblerCreationState creationState) { @@ -55,7 +56,7 @@ public ReactiveEntityJoinedFetchInitializer( lockMode, identifierFetch, discriminatorFetch, - null, + rowIdResult, creationState ); this.referencedFetchable = referencedFetchable; From af3250e8ad63f7eaad73f84803d9854943e24b49 Mon Sep 17 00:00:00 2001 From: Davide D'Alto Date: Fri, 25 Aug 2023 16:02:32 +0200 Subject: [PATCH 3/6] [#1744] Add test for `@RowId` --- .../hibernate/reactive/RowIdUpdateTest.java | 209 ++++++++++++++++++ 1 file changed, 209 insertions(+) create mode 100644 hibernate-reactive-core/src/test/java/org/hibernate/reactive/RowIdUpdateTest.java diff --git a/hibernate-reactive-core/src/test/java/org/hibernate/reactive/RowIdUpdateTest.java b/hibernate-reactive-core/src/test/java/org/hibernate/reactive/RowIdUpdateTest.java new file mode 100644 index 000000000..5abe53f35 --- /dev/null +++ b/hibernate-reactive-core/src/test/java/org/hibernate/reactive/RowIdUpdateTest.java @@ -0,0 +1,209 @@ +/* Hibernate, Relational Persistence for Idiomatic Java + * + * SPDX-License-Identifier: Apache-2.0 + * Copyright: Red Hat Inc. and Hibernate Authors + */ +package org.hibernate.reactive; + +import java.util.Collection; +import java.util.List; + +import org.hibernate.annotations.RowId; +import org.hibernate.boot.registry.StandardServiceRegistryBuilder; +import org.hibernate.cfg.Configuration; +import org.hibernate.reactive.testing.DBSelectionExtension; +import org.hibernate.reactive.testing.SqlStatementTracker; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.RegisterExtension; + +import io.vertx.junit5.VertxTestContext; +import jakarta.persistence.CascadeType; +import jakarta.persistence.Column; +import jakarta.persistence.Entity; +import jakarta.persistence.Id; +import jakarta.persistence.MapsId; +import jakarta.persistence.OneToOne; +import jakarta.persistence.Table; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.hibernate.reactive.containers.DatabaseConfiguration.DBType.DB2; +import static org.hibernate.reactive.containers.DatabaseConfiguration.DBType.ORACLE; +import static org.hibernate.reactive.testing.DBSelectionExtension.skipTestsFor; + +/** + * Adapted from the test with the same name in Hibernate ORM: {@literal org.hibernate.orm.test.rowid.RowIdUpdateTest} + */ +public class RowIdUpdateTest extends BaseReactiveTest { + + // Db2: Exception: IllegalStateException: Needed to have 6 in buffer but only had 0 + // Oracle: Vert.x driver doesn't support RowId type parameters + @RegisterExtension + public final DBSelectionExtension skip = skipTestsFor( DB2, ORACLE ); + + private static SqlStatementTracker sqlTracker; + + @Override + protected Collection> annotatedEntities() { + return List.of( ParentEntity.class, SimpleEntity.class ); + } + + @Override + protected Configuration constructConfiguration() { + Configuration configuration = super.constructConfiguration(); + sqlTracker = new SqlStatementTracker( RowIdUpdateTest::isUsingRowId, configuration.getProperties() ); + return configuration; + } + + @Override + protected void addServices(StandardServiceRegistryBuilder builder) { + sqlTracker.registerService( builder ); + } + + private static boolean isUsingRowId(String s) { + return s.toLowerCase().startsWith( "update" ); + } + + @BeforeEach + public void prepareDb(VertxTestContext context) { + test( context, getMutinySessionFactory().withTransaction( session -> session.persistAll( + new SimpleEntity( 1L, "initial_status" ), + new ParentEntity( 2L, new SimpleEntity( 2L, "initial_status" ) ) + ) ) ); + } + + @Test + public void testSimpleUpdateSameTransaction(VertxTestContext context) { + sqlTracker.clear(); + test( context, getMutinySessionFactory() + .withTransaction( session -> { + final SimpleEntity simpleEntity = new SimpleEntity( 3L, "initial_status" ); + return session.persist( simpleEntity ) + .call( session::flush ) + .invoke( () -> simpleEntity.setStatus( "new_status" ) ); + } ) + .chain( () -> getMutinySessionFactory() + .withSession( session -> session.find( SimpleEntity.class, 3L ) ) ) + // the update should have used the primary key, as the row-id value is not available + .invoke( RowIdUpdateTest::shouldUsePrimaryKey ) + .invoke( entity -> assertThat( entity ).hasFieldOrPropertyWithValue( "status", "new_status" ) ) + ); + } + + @Test + public void testRelatedUpdateSameTransaction(VertxTestContext context) { + sqlTracker.clear(); + test( context, getMutinySessionFactory() + .withTransaction( session -> { + final SimpleEntity simple = new SimpleEntity( 4L, "initial_status" ); + final ParentEntity parent = new ParentEntity( 4L, simple ); + return session.persist( parent ) + .call( session::flush ) + .invoke( () -> parent.getChild().setStatus( "new_status" ) ); + } ) + .chain( () -> getMutinySessionFactory() + .withSession( session -> session.find( SimpleEntity.class, 4L ) ) ) + // the update should have used the primary key, as the row-id value is not available + .invoke( RowIdUpdateTest::shouldUsePrimaryKey ) + .invoke( entity -> assertThat( entity ).hasFieldOrPropertyWithValue( "status", "new_status" ) ) + ); + } + + @Test + public void testSimpleUpdateDifferentTransaction(VertxTestContext context) { + sqlTracker.clear(); + test( context, getMutinySessionFactory() + .withTransaction( session -> session + .find( SimpleEntity.class, 1L ) + .invoke( entity -> entity.setStatus( "new_status" ) ) + ) + .chain( () -> getMutinySessionFactory() + .withSession( session -> session.find( SimpleEntity.class, 1L ) ) ) + .invoke( RowIdUpdateTest::shouldUseRowId ) + .invoke( entity -> assertThat( entity ).hasFieldOrPropertyWithValue( "status", "new_status" ) ) + ); + } + + @Test + public void testRelatedUpdateRelatedDifferentTransaction(VertxTestContext context) { + sqlTracker.clear(); + test( context, getMutinySessionFactory() + .withTransaction( session -> session + .find( ParentEntity.class, 2L ) + .invoke( entity -> entity.getChild().setStatus( "new_status" ) ) + ) + .invoke( RowIdUpdateTest::shouldUseRowId ) + .chain( () -> getMutinySessionFactory() + .withSession( session -> session.find( SimpleEntity.class, 2L ) ) ) + .invoke( entity -> assertThat( entity ) + .hasFieldOrPropertyWithValue( "status", "new_status" ) + ) + ); + } + + private static void shouldUsePrimaryKey() { + assertThat( sqlTracker.getLoggedQueries() ).hasSize( 1 ); + assertThat( sqlTracker.getLoggedQueries().get( 0 ) ) + .matches( "update SimpleEntity set status=.+ where primary_key=.+" ); + } + + private static void shouldUseRowId() { + // Not all databases have a rowId column + String rowId = getDialect().rowId( "" ); + String column = rowId == null ? "primary_key" : rowId; + assertThat( sqlTracker.getLoggedQueries() ).hasSize( 1 ); + assertThat( sqlTracker.getLoggedQueries().get( 0 ) ) + .matches( "update SimpleEntity set status=.+ where " + column + "=.+" ); + } + + @Entity(name = "SimpleEntity") + @Table(name = "SimpleEntity") + @RowId + public static class SimpleEntity { + @Id + @Column(name = "primary_key") + public Long primaryKey; + + public String status; + + public SimpleEntity() { + } + + public SimpleEntity(Long primaryKey, String status) { + this.primaryKey = primaryKey; + this.status = status; + } + + public String getStatus() { + return status; + } + + public void setStatus(String status) { + this.status = status; + } + } + + @Entity(name = "ParentEntity") + @Table(name = "ParentEntity") + public static class ParentEntity { + @Id + public Long id; + + @OneToOne(cascade = CascadeType.ALL) + @MapsId + public SimpleEntity child; + + public ParentEntity() { + } + + public ParentEntity(Long id, SimpleEntity child) { + this.id = id; + this.child = child; + } + + public SimpleEntity getChild() { + return child; + } + } +} From 0363839a1bdd856e487311cd04dd8545d083551a Mon Sep 17 00:00:00 2001 From: Davide D'Alto Date: Fri, 1 Sep 2023 11:10:48 +0200 Subject: [PATCH 4/6] [#1744] Update ORM version in README --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 8d25823aa..bac7298e9 100644 --- a/README.md +++ b/README.md @@ -37,7 +37,7 @@ Hibernate Reactive has been tested with: - CockroachDB 22.1 - MS SQL Server 2019 - Oracle 21.3 -- [Hibernate ORM][] 6.2.7.Final +- [Hibernate ORM][] 6.2.8.Final - [Vert.x Reactive PostgreSQL Client](https://vertx.io/docs/vertx-pg-client/java/) 4.4.5 - [Vert.x Reactive MySQL Client](https://vertx.io/docs/vertx-mysql-client/java/) 4.4.5 - [Vert.x Reactive Db2 Client](https://vertx.io/docs/vertx-db2-client/java/) 4.4.5 From f6ef821093702444c5a48327786c0fdefec97f14 Mon Sep 17 00:00:00 2001 From: Davide D'Alto Date: Sat, 26 Aug 2023 08:53:10 +0200 Subject: [PATCH 5/6] Fix field names for tests with boolean converter --- .../org/hibernate/reactive/schema/BasicTypesTestEntity.java | 4 ++-- .../reactive/types/BasicTypesAndCallbacksForAllDBsTest.java | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/hibernate-reactive-core/src/test/java/org/hibernate/reactive/schema/BasicTypesTestEntity.java b/hibernate-reactive-core/src/test/java/org/hibernate/reactive/schema/BasicTypesTestEntity.java index 7ea3ada33..75567438d 100644 --- a/hibernate-reactive-core/src/test/java/org/hibernate/reactive/schema/BasicTypesTestEntity.java +++ b/hibernate-reactive-core/src/test/java/org/hibernate/reactive/schema/BasicTypesTestEntity.java @@ -60,10 +60,10 @@ public class BasicTypesTestEntity { Byte fieldByte; @Convert(converter = org.hibernate.type.YesNoConverter.class) - Boolean booleanTrueFalse; + Boolean booleanYesNo; @Convert(converter = org.hibernate.type.TrueFalseConverter.class) - Boolean booleanYesNo; + Boolean booleanTrueFalse; @Convert(converter = org.hibernate.type.NumericBooleanConverter.class) Boolean booleanNumeric; diff --git a/hibernate-reactive-core/src/test/java/org/hibernate/reactive/types/BasicTypesAndCallbacksForAllDBsTest.java b/hibernate-reactive-core/src/test/java/org/hibernate/reactive/types/BasicTypesAndCallbacksForAllDBsTest.java index 3c816665c..9d8a34d9f 100644 --- a/hibernate-reactive-core/src/test/java/org/hibernate/reactive/types/BasicTypesAndCallbacksForAllDBsTest.java +++ b/hibernate-reactive-core/src/test/java/org/hibernate/reactive/types/BasicTypesAndCallbacksForAllDBsTest.java @@ -564,10 +564,10 @@ private static class Basic { Byte fieldByte; @Convert(converter = org.hibernate.type.YesNoConverter.class) - Boolean booleanTrueFalse; + Boolean booleanYesNo; @Convert(converter = org.hibernate.type.TrueFalseConverter.class) - Boolean booleanYesNo; + Boolean booleanTrueFalse; @Convert(converter = org.hibernate.type.NumericBooleanConverter.class) Boolean booleanNumeric; From 156a48668644ac93421fff71e5900ac7d50250c9 Mon Sep 17 00:00:00 2001 From: Davide D'Alto Date: Fri, 4 Aug 2023 15:23:41 +0200 Subject: [PATCH 6/6] Remove duplicated MutinyMain A mistake, this class is in the examples. --- .../reactive/example/MutinyMain.java | 414 ------------------ 1 file changed, 414 deletions(-) delete mode 100644 hibernate-reactive-core/src/test/java/org/hibernate/reactive/example/MutinyMain.java diff --git a/hibernate-reactive-core/src/test/java/org/hibernate/reactive/example/MutinyMain.java b/hibernate-reactive-core/src/test/java/org/hibernate/reactive/example/MutinyMain.java deleted file mode 100644 index cb242e052..000000000 --- a/hibernate-reactive-core/src/test/java/org/hibernate/reactive/example/MutinyMain.java +++ /dev/null @@ -1,414 +0,0 @@ -/* Hibernate, Relational Persistence for Idiomatic Java - * - * SPDX-License-Identifier: Apache-2.0 - * Copyright: Red Hat Inc. and Hibernate Authors - */ -package org.hibernate.reactive.example; - -import io.vertx.junit5.Timeout; -import io.vertx.junit5.VertxTestContext; -import jakarta.persistence.*; -import jakarta.persistence.criteria.*; -import org.hibernate.reactive.BaseReactiveTest; -import org.jetbrains.annotations.NotNull; -import org.junit.jupiter.api.Test; - -import java.time.LocalDate; -import java.util.ArrayList; -import java.util.Collection; -import java.util.List; - -import static jakarta.persistence.FetchType.LAZY; -import static java.lang.System.out; -import static java.time.Month.*; -import static java.util.concurrent.TimeUnit.MINUTES; - -@Timeout(value = 10, timeUnit = MINUTES) - -public class MutinyMain extends BaseReactiveTest { - - @Override - protected Collection> annotatedEntities() { - return List.of( Book.class, Author.class ); - } - - @Test - public void testWithInsert(VertxTestContext context) { - out.println( "== Mutiny API Example ==" ); - - // obtain a factory for reactive sessions based on the - // standard JPA configuration properties specified in - // resources/META-INF/persistence.xml - - // define some test data - Author author1 = new Author("Iain M. Banks"); - Author author2 = new Author("Neal Stephenson"); - Book book1 = new Book("1-85723-235-6", "Feersum Endjinn", author1, LocalDate.of(1994, JANUARY, 1)); - Book book2 = new Book("0-380-97346-4", "Cryptonomicon", author2, LocalDate.of(1999, MAY, 1)); - Book book3 = new Book("0-553-08853-X", "Snow Crash", author2, LocalDate.of(1992, JUNE, 1)); - author1.getBooks().add(book1); - author2.getBooks().add(book2); - author2.getBooks().add(book3); - - CriteriaBuilder builder = getSessionFactory().getCriteriaBuilder(); - CriteriaQuery query = builder.createQuery( Book.class ); - Root b = query.from( Book.class ); - b.fetch( "author" ); - ParameterExpression t = builder.parameter( String.class ); - query.where( builder.equal( b.get( "title" ), t ) ); - query.orderBy( builder.asc( b.get( "isbn" ) ) ); - - CriteriaUpdate update = builder.createCriteriaUpdate( Book.class ); - b = update.from( Book.class ); - update.where( builder.equal( b.get( "title" ), t ) ); - update.set( b.get( "title" ), "XXX" ); - - test( - context, - getMutinySessionFactory().withStatelessSession(session -> - session.withTransaction(tx -> session.insertAll(author1, author2, book1, book2, book3) - )) - .chain(() -> - getMutinySessionFactory().withStatelessSession( - session -> session.get(Author.class, author1.getId()) - .invoke(author -> out.println("Author.name: " + author.getName()))) - ) - .chain(() -> - getMutinySessionFactory().withStatelessSession( - session -> session.get(Book.class, book3.getId()) - .invoke(book -> out.println("Book.title: " + book.getTitle()))) - ).chain(() -> - getMutinySessionFactory().withStatelessSession( - session -> session.createNativeQuery( - "select book.title, author.name from books book join authors author on book.author_id = author.id order by book.title desc" -// ,Object.class - ) - .getResultList() - .invoke( rows -> { - List topArray = rows; - - for( Object row : topArray ) { - final Object[] theRowArray = (Object[])row; - out.printf("%s : (%s)\n", theRowArray[0], theRowArray[1]); - } - -// rows.forEach( -// row -> out.printf("%s (%s)\n", row) -// ) - } ) - ) - ) - ); - } - - @Test - public void test(VertxTestContext context) { - out.println( "== Mutiny API Example ==" ); - - // obtain a factory for reactive sessions based on the - // standard JPA configuration properties specified in - // resources/META-INF/persistence.xml - - // define some test data - Author author1 = new Author("Iain M. Banks"); - Author author2 = new Author("Neal Stephenson"); - Book book1 = new Book("1-85723-235-6", "Feersum Endjinn", author1, LocalDate.of(1994, JANUARY, 1)); - Book book2 = new Book("0-380-97346-4", "Cryptonomicon", author2, LocalDate.of(1999, MAY, 1)); - Book book3 = new Book("0-553-08853-X", "Snow Crash", author2, LocalDate.of(1992, JUNE, 1)); - author1.getBooks().add(book1); - author2.getBooks().add(book2); - author2.getBooks().add(book3); - - CriteriaBuilder builder = getSessionFactory().getCriteriaBuilder(); - CriteriaQuery query = builder.createQuery( Book.class ); - Root b = query.from( Book.class ); - b.fetch( "author" ); - ParameterExpression t = builder.parameter( String.class ); - query.where( builder.equal( b.get( "title" ), t ) ); - query.orderBy( builder.asc( b.get( "isbn" ) ) ); - - CriteriaUpdate update = builder.createCriteriaUpdate( Book.class ); - b = update.from( Book.class ); - update.where( builder.equal( b.get( "title" ), t ) ); - update.set( b.get( "title" ), "XXX" ); - - test( - context, - getMutinySessionFactory().withTransaction( (session, tx) -> session - .persistAll( author1, author2 ) - .call( session::flush ) - .chain( () -> session.find( Book.class, book1.getId() ) - .invoke( singleBook -> out.println( book1.getTitle() + " is a great book!" ) ) ) - ).chain( () -> - getMutinySessionFactory().withSession( - session -> session.find( Author.class, author1.getId(), author2.getId() ) - .invoke( authors -> authors.forEach( author -> out.println("Author.name: " + author.getName() ) ) ) - ) - ) - - /* - test( - context, - openSession() - .thenCompose( session -> session.persist( author1, author2 ) - .thenCompose( v -> session.flush() ) - ) - .thenCompose( v -> openSession() ) - .thenCompose( session -> session.createQuery( query ) - .setParameter( t, "Snow Crash" ) - .getResultList() ) - .thenAccept( books -> { - assertEquals( 1, books.size() ); - books.forEach( book -> { - assertNotNull( book.id ); - assertNotNull( book.title ); - assertNotNull( book.isbn ); - assertEquals( "Snow Crash", book.title ); - } ); - } ) - - .thenCompose( v -> openSession() ) - .thenCompose( session -> session.createQuery( update ) - .setParameter( t, "Snow Crash" ) - .executeUpdate() ) - .thenCompose( v -> openSession() ) - .thenCompose( session -> session.createQuery( delete ) - .setParameter( t, "Snow Crash" ) - .executeUpdate() ) - ); - */ - ); - } - - /* - try { - // obtain a reactive session - factory.withTransaction( - // persist the Authors with their Books in a transaction - (session, tx) -> session.persistAll( author1, author2 ) - ) - // wait for it to finish - .await().indefinitely(); - - factory.withSession( - // retrieve a Book - session -> session.find( Book.class, book1.getId() ) - // print its title - .invoke( book -> out.println( book.getTitle() + " is a great book!" ) ) - ) - .await().indefinitely(); - - factory.withSession( - // retrieve both Authors at once - session -> session.find( Author.class, author1.getId(), author2.getId() ) - .invoke( authors -> authors.forEach( author -> out.println( author.getName() ) ) ) - ) - .await().indefinitely(); - - factory.withSession( - // retrieve an Author - session -> session.find( Author.class, author2.getId() ) - // lazily fetch their books - .chain( author -> fetch( author.getBooks() ) - // print some info - .invoke( books -> { - out.println( author.getName() + " wrote " + books.size() + " books" ); - books.forEach( book -> out.println( book.getTitle() ) ); - } ) - ) - ) - .await().indefinitely(); - - factory.withSession( - // retrieve the Author lazily from a Book - session -> session.find( Book.class, book1.getId() ) - // fetch a lazy field of the Book - .chain( book -> fetch( book.getAuthor() ) - // print the lazy field - .invoke( author -> out.printf( "%s wrote '%s'\n", author.getName(), book1.getTitle() ) ) - ) - ) - .await().indefinitely(); - - factory.withSession( - // query the Book titles - session -> session.createQuery( - "select title, author.name from Book order by title desc", - Object[].class - ) - .getResultList() - .invoke( rows -> rows.forEach( - row -> out.printf( "%s (%s)\n", row[0], row[1] ) - ) ) - ) - .await().indefinitely(); - - factory.withSession( - // query the entire Book entities - session -> session.createQuery( - "from Book book join fetch book.author order by book.title desc", - Book.class - ) - .getResultList() - .invoke( books -> books.forEach( - b -> out.printf( - "%s: %s (%s)\n", - b.getIsbn(), - b.getTitle(), - b.getAuthor().getName() - ) - ) ) - ) - .await().indefinitely(); - - factory.withSession( - // use a criteria query - session -> { - CriteriaQuery query = factory.getCriteriaBuilder().createQuery( Book.class ); - Root a = query.from( Author.class ); - Join b = a.join( author1.getBooks() ); - query.where( a.get( author1.getName() ).in( "Neal Stephenson", "William Gibson" ) ); - query.select( b ); - return session.createQuery( query ).getResultList().invoke( - books -> books.forEach( book -> out.println( book.getTitle() ) ) - ); - } - ) - .await().indefinitely(); - - factory.withSession( - // retrieve a Book - session -> session.find( Book.class, book1.getId() ) - // fetch a lazy field of the Book - .call( book -> session.fetch( book, book1.getPublished() ) - // print one lazy field - .invoke( published -> out.printf( - "'%s' was published in %d\n", - book.getTitle(), - published.getYear() - ) ) - ) - .call( book -> session.fetch( book, book1.coverImage ) - // print the other lazy field - .invoke( coverImage -> out.println( new String( coverImage ) ) ) - ) - ) - .await().indefinitely(); - - factory.withTransaction( - // retrieve a Book - (session, tx) -> session.find( Book.class, book2.getId() ) - // delete the Book - .chain( session::remove ) - ) - .await().indefinitely(); - - factory.withTransaction( - // delete all the Books in a transaction - (session, tx) -> session.createQuery( "delete Book" ).executeUpdate() - //delete all the Authors - .call( () -> session.createQuery( "delete Author" ).executeUpdate() ) - ) - .await().indefinitely(); - - } - finally { - // remember to shut down the factory - factory.close(); - } - }} - */ - - @Entity - @Table(name="authors") - public static class Author { - @Id - @GeneratedValue - private Integer id; - - @NotNull - private String name; - - @OneToMany(mappedBy = "author", cascade = CascadeType.PERSIST) - private List books = new ArrayList<>(); - - public Author(String name) { - super(); - this.name = name; - } - - public Author() {} - - Integer getId() { - return id; - } - - String getName() { - return name; - } - - List getBooks() { - return books; - } - } - - - @Entity - @Table(name="books") - public static class Book { - @Id - @GeneratedValue - private Integer id; - - private String isbn; - - @NotNull - private String title; - - @Basic(fetch = LAZY) - @NotNull - private LocalDate published; - - @Basic(fetch = LAZY) - public byte[] coverImage; - - @NotNull - @ManyToOne(fetch = LAZY) - private Author author; - - public Book(String isbn, String title, Author author, LocalDate published) { - super(); - this.title = title; - this.isbn = isbn; - this.author = author; - this.published = published; - this.coverImage = ("Cover image for '" + title + "'").getBytes(); - } - - public Book() {} - - Integer getId() { - return id; - } - - String getIsbn() { - return isbn; - } - - String getTitle() { - return title; - } - - Author getAuthor() { - return author; - } - - LocalDate getPublished() { - return published; - } - - byte[] getCoverImage() { - return coverImage; - } - } -}