From 74f8976931ac6ae9c3e9219b910f241499d7b4e0 Mon Sep 17 00:00:00 2001 From: Gavin King Date: Sat, 12 Jul 2025 20:53:02 +0200 Subject: [PATCH 01/32] demote many DEBUG-level log messages to TRACE since Quarkus insists on doing something completely crazy with our INFO level --- .../boot/cfgxml/internal/ConfigLoader.java | 10 +-- .../boot/internal/BootstrapContextImpl.java | 10 +-- .../boot/internal/ClassLoaderAccessImpl.java | 11 ++- .../InFlightMetadataCollectorImpl.java | 8 +- .../boot/jaxb/internal/AbstractBinder.java | 1 - .../jaxb/internal/CacheableFileXmlSource.java | 4 +- .../boot/jaxb/internal/MappingBinder.java | 6 +- .../stax/LocalXmlResourceResolver.java | 10 +-- .../internal/AttributeConverterManager.java | 7 +- .../boot/model/internal/AnnotatedColumn.java | 10 +-- .../boot/model/internal/CollectionBinder.java | 18 ++--- .../model/internal/CollectionSecondPass.java | 8 +- .../boot/model/internal/EmbeddableBinder.java | 4 +- .../boot/model/internal/EntityBinder.java | 12 +-- .../boot/model/internal/FilterDefBinder.java | 4 +- .../boot/model/internal/QueryBinder.java | 27 ++++--- .../internal/ResultSetMappingSecondPass.java | 2 +- .../boot/model/relational/Namespace.java | 4 +- ...AnnotationMetadataSourceProcessorImpl.java | 6 +- .../internal/hbm/EntityHierarchyBuilder.java | 6 +- .../internal/hbm/FetchProfileBinder.java | 2 +- .../internal/hbm/FilterDefinitionBinder.java | 2 +- .../IdentifierGeneratorDefinitionBinder.java | 2 +- .../source/internal/hbm/MappingDocument.java | 2 +- .../source/internal/hbm/ModelBinder.java | 76 ++++++++++--------- .../internal/hbm/TypeDefinitionBinder.java | 4 +- .../xml/internal/ManagedTypeProcessor.java | 4 +- .../internal/PersistenceUnitMetadataImpl.java | 20 ++--- .../query/HbmResultSetMappingDescriptor.java | 26 +++---- ...tHbmResultSetMappingDescriptorBuilder.java | 3 +- .../query/SqlResultSetMappingDescriptor.java | 5 +- .../BootstrapServiceRegistryImpl.java | 10 +-- .../internal/StrategySelectorBuilder.java | 4 +- .../internal/StrategySelectorImpl.java | 16 ++-- .../boot/spi/XmlMappingBinderAccess.java | 2 +- .../hibernate/boot/xsd/LocalXsdResolver.java | 3 +- .../BiDirectionalAssociationHandler.java | 4 +- .../internal/bytebuddy/EnhancerImpl.java | 20 ++--- .../bytebuddy/FieldAccessEnhancer.java | 2 +- .../PersistentAttributeTransformer.java | 6 +- .../internal/CollectionCacheInvalidator.java | 8 +- .../cache/internal/EnabledCaching.java | 28 +++---- .../cache/internal/QueryResultsCacheImpl.java | 40 +++++----- .../internal/RegionFactoryInitiator.java | 10 +-- .../internal/TimestampsCacheEnabledImpl.java | 18 ++--- .../AbstractCachedDomainDataAccess.java | 2 +- .../spi/support/AbstractReadWriteAccess.java | 52 ++++++------- .../spi/support/DomainDataRegionTemplate.java | 52 ++++--------- .../spi/support/EntityReadOnlyAccess.java | 6 +- .../java/org/hibernate/cfg/Configuration.java | 4 +- .../temptable/TemporaryTableHelper.java | 4 +- .../engine/internal/Collections.java | 18 ++--- .../internal/NaturalIdResolutionsImpl.java | 6 +- .../internal/StatefulPersistenceContext.java | 4 +- .../internal/StandardRefCursorSupport.java | 2 +- .../internal/JdbcEnvironmentInitiator.java | 18 ++--- .../jdbc/env/spi/IdentifierHelperBuilder.java | 8 +- .../jdbc/internal/JdbcCoordinatorImpl.java | 4 +- .../engine/jndi/internal/JndiServiceImpl.java | 6 +- .../org/hibernate/engine/spi/ActionQueue.java | 6 +- .../hibernate/engine/spi/CollectionEntry.java | 6 +- .../engine/spi/EffectiveEntityGraph.java | 37 ++++----- .../AbstractFlushingEventListener.java | 2 +- .../internal/AbstractSaveEventListener.java | 2 +- .../EntityCopyAllowedLoggedObserver.java | 10 +-- .../EntityCopyObserverFactoryInitiator.java | 12 ++- .../internal/EventListenerGroupImpl.java | 18 ++--- .../internal/GeneratedValuesHelper.java | 2 +- .../graph/internal/parse/GraphParser.java | 20 ++--- .../org/hibernate/id/IncrementGenerator.java | 8 +- .../id/enhanced/SequenceStructure.java | 4 +- .../internal/IntegratorServiceImpl.java | 2 +- .../hibernate/internal/NaturalIdHelper.java | 2 +- .../internal/SessionFactoryImpl.java | 14 ++-- .../internal/SessionFactoryRegistry.java | 8 +- .../SessionFactoryRegistryMessageLogger.java | 3 +- .../org/hibernate/internal/SessionImpl.java | 10 +-- .../internal/StatelessSessionImpl.java | 9 +-- .../internal/log/ConnectionAccessLogger.java | 9 +-- .../jpa/HibernatePersistenceProvider.java | 10 +-- .../PersistenceUnitInfoDescriptor.java | 5 +- .../jpa/boot/spi/ProviderChecker.java | 2 +- .../internal/util/FlushModeTypeHelper.java | 4 +- .../jpa/internal/util/LogHelper.java | 2 +- .../AbstractCollectionBatchLoader.java | 8 +- .../internal/AbstractEntityBatchLoader.java | 8 +- .../CollectionBatchLoaderArrayParam.java | 12 +-- .../CollectionBatchLoaderInPredicate.java | 8 +- .../internal/EntityBatchLoaderArrayParam.java | 8 +- .../EntityBatchLoaderInPredicate.java | 14 ++-- .../internal/BaseNaturalIdLoadAccessImpl.java | 4 +- .../SimpleNaturalIdLoadAccessImpl.java | 4 +- .../org/hibernate/mapping/BasicValue.java | 2 +- .../java/org/hibernate/mapping/Table.java | 4 +- .../internal/BasicValuedCollectionPart.java | 6 +- .../internal/MappingModelCreationHelper.java | 6 +- .../internal/MappingModelCreationProcess.java | 10 +-- .../internal/PluralAttributeMappingImpl.java | 12 +-- .../mapping/ordering/ast/PathConsumer.java | 14 ++-- .../domain/internal/JpaMetamodelImpl.java | 9 +-- .../AbstractCollectionPersister.java | 13 ++-- .../collection/BasicCollectionPersister.java | 16 ++-- .../collection/OneToManyPersister.java | 16 ++-- .../AbstractUpdateRowsCoordinator.java | 2 +- .../DeleteRowsCoordinatorStandard.java | 9 ++- ...DeleteRowsCoordinatorTablePerSubclass.java | 12 +-- .../InsertRowsCoordinatorStandard.java | 9 ++- ...InsertRowsCoordinatorTablePerSubclass.java | 28 +++---- .../mutation/RemoveCoordinatorStandard.java | 7 +- .../RemoveCoordinatorTablePerSubclass.java | 7 +- .../entity/JoinedSubclassEntityPersister.java | 2 +- .../mutation/AbstractMutationCoordinator.java | 5 +- .../internal/BasicDotIdentifierConsumer.java | 28 +++---- .../internal/QualifiedJoinPathConsumer.java | 2 +- .../hql/internal/SemanticQueryBuilder.java | 4 +- .../hql/internal/SqmPathRegistryImpl.java | 25 +++--- .../hql/internal/SqmTreeCreationHelper.java | 2 +- .../hql/internal/StandardHqlTranslator.java | 4 +- .../internal/NamedObjectRepositoryImpl.java | 10 +-- .../QueryInterpretationCacheStandardImpl.java | 21 ++--- .../internal/ResultMementoEntityStandard.java | 8 +- .../DomainResultCreationStateImpl.java | 4 +- .../query/spi/AbstractQueryParameter.java | 2 +- .../query/spi/MutableQueryOptions.java | 5 +- .../sqm/function/SqmFunctionRegistry.java | 16 ++-- .../sqm/internal/SqmCriteriaNodeBuilder.java | 4 +- .../query/sqm/internal/SqmTreePrinter.java | 24 +++--- .../GlobalTemporaryTableStrategy.java | 4 +- .../temptable/PersistentTableStrategy.java | 8 +- .../RestrictedDeleteExecutionDelegate.java | 2 +- .../sqm/sql/BaseSqmToSqlAstConverter.java | 10 +-- .../query/sqm/sql/FromClauseIndex.java | 2 +- .../expression/AbstractSqmExpression.java | 4 +- .../AbstractLogicalConnectionImplementor.java | 4 +- .../LogicalConnectionManagedImpl.java | 8 +- .../LogicalConnectionProvidedImpl.java | 6 +- .../internal/ResultsetsTrackingContainer.java | 2 +- .../resource/jdbc/spi/JdbcEventHandler.java | 2 +- .../DdlTransactionIsolatorNonJtaImpl.java | 2 +- ...sourceLocalTransactionCoordinatorImpl.java | 6 +- .../jta/internal/JtaIsolationDelegate.java | 4 +- .../JtaTransactionCoordinatorImpl.java | 4 +- .../SynchronizationRegistryStandardImpl.java | 3 +- .../result/internal/OutputsImpl.java | 4 +- .../internal/AbstractServiceRegistryImpl.java | 10 +-- .../SessionFactoryServiceRegistryImpl.java | 4 +- .../org/hibernate/sql/ast/SqlTreePrinter.java | 13 ++-- .../ast/spi/SimpleFromClauseAccessImpl.java | 12 +-- .../sql/ast/spi/SqlAliasBaseImpl.java | 2 +- .../sql/ast/tree/expression/SqlTuple.java | 11 --- .../sql/ast/tree/from/TableGroupJoin.java | 2 +- .../JdbcSelectExecutorStandardImpl.java | 10 +-- .../jdbc/OptionalTableUpdateOperation.java | 4 +- .../graph/DomainResultGraphPrinter.java | 21 ++--- .../internal/EmbeddableInitializerImpl.java | 4 +- .../graph/tuple/TupleResultAssembler.java | 4 +- .../NavigablePathMapToInitializer.java | 50 ++++++------ .../sql/results/internal/ResultsHelper.java | 14 ++-- .../stat/internal/StatisticsInitiator.java | 2 +- .../internal/AbstractSchemaMigrator.java | 4 +- .../internal/AbstractSchemaValidator.java | 2 +- .../tool/schema/internal/Helper.java | 4 +- .../schema/internal/SchemaCreatorImpl.java | 2 +- .../schema/internal/SchemaDropperImpl.java | 2 +- ...onnectionAccessConnectionProviderImpl.java | 2 +- ...onnectionAccessProvidedConnectionImpl.java | 2 +- .../exec/ScriptTargetOutputToFile.java | 4 +- .../exec/ScriptTargetOutputToUrl.java | 2 +- .../org/hibernate/type/BasicTypeRegistry.java | 12 +-- .../descriptor/jdbc/spi/JdbcTypeRegistry.java | 4 +- .../descriptor/sql/spi/DdlTypeRegistry.java | 2 +- .../hibernate/type/spi/TypeConfiguration.java | 6 +- 172 files changed, 747 insertions(+), 831 deletions(-) diff --git a/hibernate-core/src/main/java/org/hibernate/boot/cfgxml/internal/ConfigLoader.java b/hibernate-core/src/main/java/org/hibernate/boot/cfgxml/internal/ConfigLoader.java index e25c28864dff..58b9615ad4d2 100644 --- a/hibernate-core/src/main/java/org/hibernate/boot/cfgxml/internal/ConfigLoader.java +++ b/hibernate-core/src/main/java/org/hibernate/boot/cfgxml/internal/ConfigLoader.java @@ -130,10 +130,7 @@ public Properties loadProperties(String resourceName) { stream.close(); } catch (IOException e) { - log.debug( - String.format( "Unable to close properties file [%s] stream", resourceName ), - e - ); + log.debug( "Unable to close properties file stream [" + resourceName + "]", e ); } } } @@ -157,10 +154,7 @@ public Properties loadProperties(File file) { stream.close(); } catch (IOException e) { - log.debug( - String.format( "Unable to close properties file [%s] stream", file.getAbsolutePath() ), - e - ); + log.debug( "Unable to close properties file stream [" + file.getAbsolutePath() + "]", e ); } } } diff --git a/hibernate-core/src/main/java/org/hibernate/boot/internal/BootstrapContextImpl.java b/hibernate-core/src/main/java/org/hibernate/boot/internal/BootstrapContextImpl.java index 5aeff4d511a3..a1208d2497cf 100644 --- a/hibernate-core/src/main/java/org/hibernate/boot/internal/BootstrapContextImpl.java +++ b/hibernate-core/src/main/java/org/hibernate/boot/internal/BootstrapContextImpl.java @@ -308,27 +308,27 @@ public void addAttributeConverterDescriptor(ConverterDescriptor descriptor) } void injectJpaTempClassLoader(ClassLoader jpaTempClassLoader) { - log.debugf( "Injecting JPA temp ClassLoader [%s] into BootstrapContext; was [%s]", jpaTempClassLoader, this.getJpaTempClassLoader() ); + log.tracef( "Injecting JPA temp ClassLoader [%s] into BootstrapContext; was [%s]", jpaTempClassLoader, this.getJpaTempClassLoader() ); this.classLoaderAccess.injectTempClassLoader( jpaTempClassLoader ); } void injectScanOptions(ScanOptions scanOptions) { - log.debugf( "Injecting ScanOptions [%s] into BootstrapContext; was [%s]", scanOptions, this.scanOptions ); + log.tracef( "Injecting ScanOptions [%s] into BootstrapContext; was [%s]", scanOptions, this.scanOptions ); this.scanOptions = scanOptions; } void injectScanEnvironment(ScanEnvironment scanEnvironment) { - log.debugf( "Injecting ScanEnvironment [%s] into BootstrapContext; was [%s]", scanEnvironment, this.scanEnvironment ); + log.tracef( "Injecting ScanEnvironment [%s] into BootstrapContext; was [%s]", scanEnvironment, this.scanEnvironment ); this.scanEnvironment = scanEnvironment; } void injectScanner(Scanner scanner) { - log.debugf( "Injecting Scanner [%s] into BootstrapContext; was [%s]", scanner, this.scannerSetting ); + log.tracef( "Injecting Scanner [%s] into BootstrapContext; was [%s]", scanner, this.scannerSetting ); this.scannerSetting = scanner; } void injectArchiveDescriptorFactory(ArchiveDescriptorFactory factory) { - log.debugf( "Injecting ArchiveDescriptorFactory [%s] into BootstrapContext; was [%s]", factory, this.archiveDescriptorFactory ); + log.tracef( "Injecting ArchiveDescriptorFactory [%s] into BootstrapContext; was [%s]", factory, this.archiveDescriptorFactory ); this.archiveDescriptorFactory = factory; } diff --git a/hibernate-core/src/main/java/org/hibernate/boot/internal/ClassLoaderAccessImpl.java b/hibernate-core/src/main/java/org/hibernate/boot/internal/ClassLoaderAccessImpl.java index 760fd239058f..d10d8ed56dcc 100644 --- a/hibernate-core/src/main/java/org/hibernate/boot/internal/ClassLoaderAccessImpl.java +++ b/hibernate-core/src/main/java/org/hibernate/boot/internal/ClassLoaderAccessImpl.java @@ -40,7 +40,6 @@ public ClassLoaderAccessImpl(ClassLoaderService classLoaderService) { } public void injectTempClassLoader(ClassLoader jpaTempClassLoader) { - log.debugf( "ClassLoaderAccessImpl#injectTempClassLoader(%s) [was %s]", jpaTempClassLoader, this.jpaTempClassLoader ); this.jpaTempClassLoader = jpaTempClassLoader; } @@ -55,18 +54,18 @@ public Class classForName(String name) { return classLoaderService.classForName( name ); } else { - log.debugf( "Not known whether passed class name [%s] is safe", name ); + log.tracef( "Not known whether passed class name [%s] is safe", name ); if ( jpaTempClassLoader == null ) { - log.debugf( + log.tracef( "No temp ClassLoader provided; using live ClassLoader " + - "for loading potentially unsafe class : %s", + "for loading potentially unsafe class: %s", name ); return classLoaderService.classForName( name ); } else { - log.debugf( - "Temp ClassLoader was provided, so we will use that : %s", + log.tracef( + "Temp ClassLoader was provided, so we will use that: %s", name ); try { diff --git a/hibernate-core/src/main/java/org/hibernate/boot/internal/InFlightMetadataCollectorImpl.java b/hibernate-core/src/main/java/org/hibernate/boot/internal/InFlightMetadataCollectorImpl.java index 8076e10d3659..10d353909be8 100644 --- a/hibernate-core/src/main/java/org/hibernate/boot/internal/InFlightMetadataCollectorImpl.java +++ b/hibernate-core/src/main/java/org/hibernate/boot/internal/InFlightMetadataCollectorImpl.java @@ -903,9 +903,9 @@ public void addImport(String importName, String className) { throw new IllegalArgumentException( "Import name or entity name is null" ); } log.tracev( "Import: {0} -> {1}", importName, className); - String old = imports.put( importName, className); + final String old = imports.put( importName, className); if ( old != null ) { - log.debugf( "import name [%s] overrode previous [{%s}]", importName, old ); + log.debugf( "Import name [%s] overrode previous [{%s}]", importName, old ); } } @@ -1953,7 +1953,7 @@ protected void secondPassCompileForeignKeys(Table table, Set done, M private void processPropertyReferences() { if ( delayedPropertyReferenceHandlers != null ) { - log.debug( "Processing association property references" ); + log.trace( "Processing association property references" ); for ( DelayedPropertyReferenceHandler delayedPropertyReferenceHandler : delayedPropertyReferenceHandlers ) { delayedPropertyReferenceHandler.process( this ); @@ -2107,7 +2107,7 @@ private void handleIdentifierValueBinding( // by tools. We want to hold off requiring classes being present until we // try to build the SF. Here, just building the Metadata, it is "ok" for an // exception to occur, the same exception will happen later as we build the SF. - log.debugf( "Ignoring exception thrown when trying to build IdentifierGenerator as part of Metadata building", e ); + log.debug( "Ignoring exception thrown when trying to build IdentifierGenerator as part of Metadata building", e ); } } diff --git a/hibernate-core/src/main/java/org/hibernate/boot/jaxb/internal/AbstractBinder.java b/hibernate-core/src/main/java/org/hibernate/boot/jaxb/internal/AbstractBinder.java index 00da6114a37b..6b2cc82f699e 100644 --- a/hibernate-core/src/main/java/org/hibernate/boot/jaxb/internal/AbstractBinder.java +++ b/hibernate-core/src/main/java/org/hibernate/boot/jaxb/internal/AbstractBinder.java @@ -99,7 +99,6 @@ private Binding doBind(XMLEventReader eventReader, Origin origi } catch (Exception e) { log.debug( "Unable to close StAX reader", e ); - } } } diff --git a/hibernate-core/src/main/java/org/hibernate/boot/jaxb/internal/CacheableFileXmlSource.java b/hibernate-core/src/main/java/org/hibernate/boot/jaxb/internal/CacheableFileXmlSource.java index 9643845d7242..0cfa4a06d2e6 100644 --- a/hibernate-core/src/main/java/org/hibernate/boot/jaxb/internal/CacheableFileXmlSource.java +++ b/hibernate-core/src/main/java/org/hibernate/boot/jaxb/internal/CacheableFileXmlSource.java @@ -118,8 +118,8 @@ private static void writeSerFile(Serializable binding, File xmlFile, File serFil binding = (Serializable) bindingWrapper.getRoot(); } try ( FileOutputStream fos = new FileOutputStream( serFile ) ) { - if ( log.isDebugEnabled() ) { - log.debugf( "Writing cache file for: %s to: %s", xmlFile.getAbsolutePath(), serFile.getAbsolutePath() ); + if ( log.isTraceEnabled() ) { + log.tracef( "Writing cache file for: %s to: %s", xmlFile.getAbsolutePath(), serFile.getAbsolutePath() ); } SerializationHelper.serialize( binding, fos ); boolean success = serFile.setLastModified( System.currentTimeMillis() ); diff --git a/hibernate-core/src/main/java/org/hibernate/boot/jaxb/internal/MappingBinder.java b/hibernate-core/src/main/java/org/hibernate/boot/jaxb/internal/MappingBinder.java index 7435690fa91d..78ef6bc753ec 100644 --- a/hibernate-core/src/main/java/org/hibernate/boot/jaxb/internal/MappingBinder.java +++ b/hibernate-core/src/main/java/org/hibernate/boot/jaxb/internal/MappingBinder.java @@ -163,8 +163,8 @@ protected Binding doBind( Origin origin) { final String rootElementLocalName = rootElementStartEvent.getName().getLocalPart(); if ( "hibernate-mapping".equals( rootElementLocalName ) ) { - if ( log.isDebugEnabled() ) { - log.debugf( "Performing JAXB binding of hbm.xml document : %s", origin.toString() ); + if ( log.isTraceEnabled() ) { + log.tracef( "Performing JAXB binding of hbm.xml document: %s", origin.toString() ); } final XMLEventReader hbmReader = new HbmEventReader( staxEventReader, xmlEventFactory ); @@ -181,7 +181,7 @@ protected Binding doBind( else { assert "entity-mappings".equals( rootElementLocalName ); try { - log.debugf( "Performing JAXB binding of orm.xml document : %s", origin.toString() ); + log.tracef( "Performing JAXB binding of orm.xml document: %s", origin.toString() ); final XMLEventReader reader = new MappingEventReader( staxEventReader, xmlEventFactory ); final JaxbEntityMappingsImpl bindingRoot = jaxb( diff --git a/hibernate-core/src/main/java/org/hibernate/boot/jaxb/internal/stax/LocalXmlResourceResolver.java b/hibernate-core/src/main/java/org/hibernate/boot/jaxb/internal/stax/LocalXmlResourceResolver.java index ea1aa9211288..8b3d482a1988 100644 --- a/hibernate-core/src/main/java/org/hibernate/boot/jaxb/internal/stax/LocalXmlResourceResolver.java +++ b/hibernate-core/src/main/java/org/hibernate/boot/jaxb/internal/stax/LocalXmlResourceResolver.java @@ -37,7 +37,7 @@ public Object resolveEntity(String publicID, String systemID, String baseURI, St log.tracef( "In resolveEntity(%s, %s, %s, %s)", publicID, systemID, baseURI, namespace ); if ( namespace != null ) { - log.debugf( "Interpreting namespace : %s", namespace ); + log.tracef( "Interpreting namespace: %s", namespace ); if ( MappingXsdSupport.latestDescriptor().getNamespaceUri().matches( namespace ) ) { return openUrlStream( MappingXsdSupport.latestDescriptor() ); } @@ -84,7 +84,7 @@ else if ( ConfigXsdSupport.cfgXsd().getNamespaceUri().matches( namespace ) ) { } if ( publicID != null || systemID != null ) { - log.debugf( "Checking public/system identifiers `%s`/`%s` as DTD references", publicID, systemID ); + log.tracef( "Checking public/system identifiers `%s`/`%s` as DTD references", publicID, systemID ); if ( MAPPING_DTD.matches( publicID, systemID ) ) { return openUrlStream( MAPPING_DTD.localSchemaUrl ); @@ -116,15 +116,15 @@ else if ( ConfigXsdSupport.cfgXsd().getNamespaceUri().matches( namespace ) ) { if ( systemID != null ) { // technically, "classpath://..." identifiers should only be declared as SYSTEM identifiers if ( systemID.startsWith( CLASSPATH_EXTENSION_URL_BASE ) ) { - log.debugf( "Recognized `classpath:` identifier; attempting to resolve on classpath [%s]", systemID ); + log.tracef( "Recognized `classpath:` identifier; attempting to resolve on classpath [%s]", systemID ); final String path = systemID.substring( CLASSPATH_EXTENSION_URL_BASE.length() ); // todo : for this to truly work consistently, we need access to ClassLoaderService final InputStream stream = resolveInLocalNamespace( path ); if ( stream == null ) { - log.debugf( "Unable to resolve [%s] on classpath", systemID ); + log.tracef( "Unable to resolve [%s] on classpath", systemID ); } else { - log.debugf( "Resolved [%s] on classpath", systemID ); + log.tracef( "Resolved [%s] on classpath", systemID ); } return stream; } diff --git a/hibernate-core/src/main/java/org/hibernate/boot/model/convert/internal/AttributeConverterManager.java b/hibernate-core/src/main/java/org/hibernate/boot/model/convert/internal/AttributeConverterManager.java index bf5664030f28..42d33297547f 100644 --- a/hibernate-core/src/main/java/org/hibernate/boot/model/convert/internal/AttributeConverterManager.java +++ b/hibernate-core/src/main/java/org/hibernate/boot/model/convert/internal/AttributeConverterManager.java @@ -112,8 +112,7 @@ public void addRegistration(RegisteredConversion conversion, BootstrapContext co // see if we have a matching entry in `attributeConverterDescriptorsByClass`. // if so, remove it. The conversion being registered will always take precedence if ( attributeConverterDescriptorsByClass != null ) { - final ConverterDescriptor removed = - attributeConverterDescriptorsByClass.remove( conversion.getConverterType() ); + final var removed = attributeConverterDescriptorsByClass.remove( conversion.getConverterType() ); if ( removed != null && log.isDebugEnabled() ) { log.debugf( "Removed potentially auto-applicable converter `%s` due to @ConverterRegistration", removed.getAttributeConverterClass().getName() ); @@ -228,8 +227,8 @@ private List> getMatches( ConverterDescriptor> matcher) { final List> matches = new ArrayList<>(); for ( ConverterDescriptor descriptor : converterDescriptors() ) { - if ( log.isDebugEnabled() ) { - log.debugf( + if ( log.isTraceEnabled() ) { + log.tracef( "Checking auto-apply AttributeConverter [%s] (domain-type=%s) for match against %s : %s.%s (type=%s)", descriptor.getAttributeConverterClass().getName(), descriptor.getDomainValueResolvedType().getSignature(), diff --git a/hibernate-core/src/main/java/org/hibernate/boot/model/internal/AnnotatedColumn.java b/hibernate-core/src/main/java/org/hibernate/boot/model/internal/AnnotatedColumn.java index 3d2bd27d3d39..270316510207 100644 --- a/hibernate-core/src/main/java/org/hibernate/boot/model/internal/AnnotatedColumn.java +++ b/hibernate-core/src/main/java/org/hibernate/boot/model/internal/AnnotatedColumn.java @@ -240,8 +240,8 @@ public AnnotatedColumn() { public void bind() { if ( isNotEmpty( formulaString ) ) { - if ( LOG.isDebugEnabled() ) { - LOG.debug( "Binding formula: " + formulaString ); + if ( LOG.isTraceEnabled() ) { + LOG.trace( "Binding formula: " + formulaString ); } formula = new Formula(); formula.setFormula( formulaString ); @@ -275,7 +275,7 @@ public void bind() { mappingColumn.setGeneratedAs( generatedAs ); } if ( LOG.isDebugEnabled() ) { - LOG.debug( "Binding column: " + logicalColumnName ); + LOG.trace( "Binding column: " + logicalColumnName ); } } } @@ -773,8 +773,8 @@ private static jakarta.persistence.Column[] overrideColumns( + " '@AttributeOverride's but the overridden property has " + overriddenCols.length + " columns (every column must have exactly one '@AttributeOverride')" ); } - if ( LOG.isDebugEnabled() ) { - LOG.debug( "Column mapping overridden for property: " + inferredData.getPropertyName() ); + if ( LOG.isTraceEnabled() ) { + LOG.trace( "Column mapping overridden for property: " + inferredData.getPropertyName() ); } return isEmpty( overriddenCols ) ? null : overriddenCols; } diff --git a/hibernate-core/src/main/java/org/hibernate/boot/model/internal/CollectionBinder.java b/hibernate-core/src/main/java/org/hibernate/boot/model/internal/CollectionBinder.java index 88b4c7e76f66..e139ebf02f45 100644 --- a/hibernate-core/src/main/java/org/hibernate/boot/model/internal/CollectionBinder.java +++ b/hibernate-core/src/main/java/org/hibernate/boot/model/internal/CollectionBinder.java @@ -1079,8 +1079,8 @@ private void setDeclaringClass(ClassDetails declaringClass) { private void bind() { collection = createCollection( propertyHolder.getPersistentClass() ); final String role = qualify( propertyHolder.getPath(), propertyName ); - if ( LOG.isDebugEnabled() ) { - LOG.debug( "Binding collection role: " + role ); + if ( LOG.isTraceEnabled() ) { + LOG.trace( "Binding collection role: " + role ); } collection.setRole( role ); collection.setMappedByProperty( mappedBy ); @@ -2803,8 +2803,8 @@ private void setLocalGenerators(Map local } private void logOneToManySecondPass() { - if ( LOG.isDebugEnabled() ) { - LOG.debug( "Binding @OneToMany through foreign key: " + safeCollectionRole() ); + if ( LOG.isTraceEnabled() ) { + LOG.trace( "Binding @OneToMany through foreign key: " + safeCollectionRole() ); } } @@ -2812,18 +2812,18 @@ private void logManyToManySecondPass( boolean isOneToMany, boolean isCollectionOfEntities, boolean isManyToAny) { - if ( LOG.isDebugEnabled() ) { + if ( LOG.isTraceEnabled() ) { if ( isCollectionOfEntities && isOneToMany ) { - LOG.debug( "Binding @OneToMany through association table: " + safeCollectionRole() ); + LOG.trace( "Binding @OneToMany through association table: " + safeCollectionRole() ); } else if ( isCollectionOfEntities ) { - LOG.debug( "Binding @ManyToMany through association table: " + safeCollectionRole() ); + LOG.trace( "Binding @ManyToMany through association table: " + safeCollectionRole() ); } else if ( isManyToAny ) { - LOG.debug( "Binding @ManyToAny: " + safeCollectionRole() ); + LOG.trace( "Binding @ManyToAny: " + safeCollectionRole() ); } else { - LOG.debug( "Binding @ElementCollection to collection table: " + safeCollectionRole() ); + LOG.trace( "Binding @ElementCollection to collection table: " + safeCollectionRole() ); } } } diff --git a/hibernate-core/src/main/java/org/hibernate/boot/model/internal/CollectionSecondPass.java b/hibernate-core/src/main/java/org/hibernate/boot/model/internal/CollectionSecondPass.java index 9fa70237a78d..9e4362928dd7 100644 --- a/hibernate-core/src/main/java/org/hibernate/boot/model/internal/CollectionSecondPass.java +++ b/hibernate-core/src/main/java/org/hibernate/boot/model/internal/CollectionSecondPass.java @@ -36,14 +36,14 @@ public CollectionSecondPass(Collection collection) { @Override public void doSecondPass(Map persistentClasses) throws MappingException { - if ( LOG.isDebugEnabled() ) { - LOG.debug( "Second pass for collection: " + collection.getRole() ); + if ( LOG.isTraceEnabled() ) { + LOG.trace( "Second pass for collection: " + collection.getRole() ); } secondPass( persistentClasses ); collection.createAllKeys(); - if ( LOG.isDebugEnabled() ) { + if ( LOG.isTraceEnabled() ) { String msg = "Mapped collection key: " + columns( collection.getKey() ); if ( collection.isIndexed() ) { msg += ", index: " + columns( ( (IndexedCollection) collection ).getIndex() ); @@ -55,7 +55,7 @@ public void doSecondPass(Map persistentClasses) else { msg += ", element: " + columns( collection.getElement() ); } - LOG.debug( msg ); + LOG.trace( msg ); } } diff --git a/hibernate-core/src/main/java/org/hibernate/boot/model/internal/EmbeddableBinder.java b/hibernate-core/src/main/java/org/hibernate/boot/model/internal/EmbeddableBinder.java index d901e84b1935..023cc1484d5b 100644 --- a/hibernate-core/src/main/java/org/hibernate/boot/model/internal/EmbeddableBinder.java +++ b/hibernate-core/src/main/java/org/hibernate/boot/model/internal/EmbeddableBinder.java @@ -452,8 +452,8 @@ static Component fillEmbeddable( ); final String subpath = getPath( propertyHolder, inferredData ); - if ( LOG.isDebugEnabled() ) { - LOG.debug( "Binding component with path: " + subpath ); + if ( LOG.isTraceEnabled() ) { + LOG.trace( "Binding component with path: " + subpath ); } final PropertyHolder subholder = buildPropertyHolder( component, diff --git a/hibernate-core/src/main/java/org/hibernate/boot/model/internal/EntityBinder.java b/hibernate-core/src/main/java/org/hibernate/boot/model/internal/EntityBinder.java index f6a80f371af6..9b06f080a102 100644 --- a/hibernate-core/src/main/java/org/hibernate/boot/model/internal/EntityBinder.java +++ b/hibernate-core/src/main/java/org/hibernate/boot/model/internal/EntityBinder.java @@ -179,8 +179,8 @@ public static void bindEntityClass( ClassDetails clazzToProcess, Map inheritanceStates, MetadataBuildingContext context) { - if ( LOG.isDebugEnabled() ) { - LOG.debug( "Binding entity from annotated class: " + clazzToProcess.getName() ); + if ( LOG.isTraceEnabled() ) { + LOG.trace( "Binding entity from annotated class: " + clazzToProcess.getName() ); } final InFlightMetadataCollector collector = context.getMetadataCollector(); @@ -1011,8 +1011,8 @@ private boolean useDiscriminatorColumnForJoined(DiscriminatorColumn discriminato if ( discriminatorColumn != null ) { final boolean ignore = buildingOptions.ignoreExplicitDiscriminatorsForJoinedInheritance(); if ( ignore ) { - if ( LOG.isDebugEnabled() ) { - LOG.debug( "Ignoring explicit @DiscriminatorColumn annotation on: " + if ( LOG.isTraceEnabled() ) { + LOG.trace( "Ignoring explicit @DiscriminatorColumn annotation on: " + annotatedClass.getName() ); } } @@ -1021,8 +1021,8 @@ private boolean useDiscriminatorColumnForJoined(DiscriminatorColumn discriminato else { final boolean createImplicit = buildingOptions.createImplicitDiscriminatorsForJoinedInheritance(); if ( createImplicit ) { - if ( LOG.isDebugEnabled() ) { - LOG.debug( "Inferring implicit @DiscriminatorColumn using defaults for: " + if ( LOG.isTraceEnabled() ) { + LOG.trace( "Inferring implicit @DiscriminatorColumn using defaults for: " + annotatedClass.getName() ); } } diff --git a/hibernate-core/src/main/java/org/hibernate/boot/model/internal/FilterDefBinder.java b/hibernate-core/src/main/java/org/hibernate/boot/model/internal/FilterDefBinder.java index dba72198c7dc..728162b18fea 100644 --- a/hibernate-core/src/main/java/org/hibernate/boot/model/internal/FilterDefBinder.java +++ b/hibernate-core/src/main/java/org/hibernate/boot/model/internal/FilterDefBinder.java @@ -95,8 +95,8 @@ public static void bindFilterDef(FilterDef filterDef, MetadataBuildingContext co parameterResolvers ); - if ( LOG.isDebugEnabled() ) { - LOG.debug( "Binding filter definition: " + filterDefinition.getFilterName() ); + if ( LOG.isTraceEnabled() ) { + LOG.trace( "Binding filter definition: " + filterDefinition.getFilterName() ); } context.getMetadataCollector().addFilterDefinition( filterDefinition ); } diff --git a/hibernate-core/src/main/java/org/hibernate/boot/model/internal/QueryBinder.java b/hibernate-core/src/main/java/org/hibernate/boot/model/internal/QueryBinder.java index b4883f980664..5bfbbd9dd9ad 100644 --- a/hibernate-core/src/main/java/org/hibernate/boot/model/internal/QueryBinder.java +++ b/hibernate-core/src/main/java/org/hibernate/boot/model/internal/QueryBinder.java @@ -80,8 +80,8 @@ public static void bindQuery( "Class or package level '@NamedQuery' annotation must specify a 'name'" ); } - if ( LOG.isDebugEnabled() ) { - LOG.debugf( "Binding named query: %s => %s", queryName, queryString ); + if ( LOG.isTraceEnabled() ) { + LOG.tracef( "Binding named query: %s => %s", queryName, queryString ); } final QueryHintDefinition hints = new QueryHintDefinition( queryName, namedQuery.hints() ); @@ -140,9 +140,10 @@ public static void bindNativeQuery( final NamedNativeQueryDefinition queryDefinition = createNamedQueryDefinition( registrationName, queryString, resultClass, resultSetMappingName, hints, location ); - if ( LOG.isDebugEnabled() ) { - LOG.debugf( "Binding named native query: %s => %s", - queryDefinition.getRegistrationName(), queryDefinition.getSqlQueryString() ); + if ( LOG.isTraceEnabled() ) { + LOG.tracef( "Binding named native query: %s => %s", + queryDefinition.getRegistrationName(), + queryDefinition.getSqlQueryString() ); } if ( isDefault ) { @@ -231,8 +232,8 @@ public static void bindNativeQuery( createQueryDefinition( namedNativeQuery, registrationName, resultSetMappingName, resultClass, namedNativeQuery.timeout(), namedNativeQuery.fetchSize(), querySpaces, location ); final NamedNativeQueryDefinition queryDefinition = builder.build(); - if ( LOG.isDebugEnabled() ) { - LOG.debugf( + if ( LOG.isTraceEnabled() ) { + LOG.tracef( "Binding named native query: %s => %s", queryDefinition.getRegistrationName(), queryDefinition.getSqlQueryString() @@ -388,9 +389,10 @@ public static void bindQuery( final NamedHqlQueryDefinitionImpl hqlQueryDefinition = builder.build(); - if ( LOG.isDebugEnabled() ) { - LOG.debugf( "Binding named query: %s => %s", - hqlQueryDefinition.getRegistrationName(), hqlQueryDefinition.getHqlString() ); + if ( LOG.isTraceEnabled() ) { + LOG.tracef( "Binding named query: %s => %s", + hqlQueryDefinition.getRegistrationName(), + hqlQueryDefinition.getHqlString() ); } context.getMetadataCollector().addNamedQuery( hqlQueryDefinition ); @@ -451,8 +453,9 @@ public static void bindNamedStoredProcedureQuery( else { context.getMetadataCollector().addNamedProcedureCallDefinition( definition ); } - LOG.debugf( "Bound named stored procedure query: %s => %s", - definition.getRegistrationName(), definition.getProcedureName() ); + LOG.tracef( "Bound named stored procedure query: %s => %s", + definition.getRegistrationName(), + definition.getProcedureName() ); } } diff --git a/hibernate-core/src/main/java/org/hibernate/boot/model/internal/ResultSetMappingSecondPass.java b/hibernate-core/src/main/java/org/hibernate/boot/model/internal/ResultSetMappingSecondPass.java index 54a206e79158..8d2331a8f91a 100644 --- a/hibernate-core/src/main/java/org/hibernate/boot/model/internal/ResultSetMappingSecondPass.java +++ b/hibernate-core/src/main/java/org/hibernate/boot/model/internal/ResultSetMappingSecondPass.java @@ -47,7 +47,7 @@ public void doSecondPass(Map persistentClasses) throws //TODO add parameters checkings // if ( ann == null ) return; // ResultSetMappingDescriptor definition = new ResultSetMappingDescriptor( ann.name() ); -// LOG.debugf( "Binding result set mapping: %s", definition.getName() ); +// LOG.tracef( "Binding result set mapping: %s", definition.getName() ); // // int entityAliasIndex = 0; // diff --git a/hibernate-core/src/main/java/org/hibernate/boot/model/relational/Namespace.java b/hibernate-core/src/main/java/org/hibernate/boot/model/relational/Namespace.java index d3b8b4f6ec7c..28fdde23e2a3 100644 --- a/hibernate-core/src/main/java/org/hibernate/boot/model/relational/Namespace.java +++ b/hibernate-core/src/main/java/org/hibernate/boot/model/relational/Namespace.java @@ -58,8 +58,8 @@ public Namespace(PhysicalNamingStrategy physicalNamingStrategy, JdbcEnvironment this.name = name; this.physicalName = physicalName( name, physicalNamingStrategy, jdbcEnvironment ); - if ( log.isDebugEnabled() ) { - log.debugf( + if ( log.isTraceEnabled() ) { + log.tracef( "Created database namespace [logicalName=%s, physicalName=%s]", name.toString(), physicalName.toString() diff --git a/hibernate-core/src/main/java/org/hibernate/boot/model/source/internal/annotations/AnnotationMetadataSourceProcessorImpl.java b/hibernate-core/src/main/java/org/hibernate/boot/model/source/internal/annotations/AnnotationMetadataSourceProcessorImpl.java index aa9957e1c59b..8b20e82d9277 100644 --- a/hibernate-core/src/main/java/org/hibernate/boot/model/source/internal/annotations/AnnotationMetadataSourceProcessorImpl.java +++ b/hibernate-core/src/main/java/org/hibernate/boot/model/source/internal/annotations/AnnotationMetadataSourceProcessorImpl.java @@ -215,7 +215,7 @@ private List orderAndFillHierarchy(LinkedHashSet ori } private void insertMappedSuperclasses(LinkedHashSet original, LinkedHashSet copy) { - final boolean debug = log.isDebugEnabled(); + final boolean traceEnabled = log.isTraceEnabled(); for ( ClassDetails clazz : original ) { if ( clazz.isInterface() ) { @@ -225,8 +225,8 @@ private void insertMappedSuperclasses(LinkedHashSet original, Link } if ( clazz.hasDirectAnnotationUsage( MappedSuperclass.class ) ) { - if ( debug ) { - log.debugf( + if ( traceEnabled ) { + log.tracef( "Skipping explicit MappedSuperclass %s, the class will be discovered analyzing the implementing class", clazz ); diff --git a/hibernate-core/src/main/java/org/hibernate/boot/model/source/internal/hbm/EntityHierarchyBuilder.java b/hibernate-core/src/main/java/org/hibernate/boot/model/source/internal/hbm/EntityHierarchyBuilder.java index 5347967db010..7ac264841f99 100644 --- a/hibernate-core/src/main/java/org/hibernate/boot/model/source/internal/hbm/EntityHierarchyBuilder.java +++ b/hibernate-core/src/main/java/org/hibernate/boot/model/source/internal/hbm/EntityHierarchyBuilder.java @@ -59,10 +59,10 @@ public EntityHierarchyBuilder() { public List buildHierarchies() throws HibernateException { if ( toBeLinkedQueue != null && !toBeLinkedQueue.isEmpty() ) { if ( log.isDebugEnabled() ) { - for ( Map.Entry> waitingListEntry : toBeLinkedQueue.entrySet() ) { + for ( var waitingListEntry : toBeLinkedQueue.entrySet() ) { for ( ExtendsQueueEntry waitingEntry : waitingListEntry.getValue() ) { log.debugf( - "Entity super-type named as extends [%s] for subclass [%s:%s] not found", + "Entity supertype named as extends [%s] for subclass [%s:%s] not found", waitingListEntry.getKey(), waitingEntry.sourceMappingDocument.getOrigin(), waitingEntry.sourceMappingDocument.determineEntityName( waitingEntry.jaxbSubEntityMapping ) @@ -71,7 +71,7 @@ public List buildHierarchies() throws HibernateExcept } } throw new HibernateException( - "Not all named super-types (extends) were found : " + toBeLinkedQueue.keySet() + "Not all named supertypes (extends) were found : " + toBeLinkedQueue.keySet() ); } diff --git a/hibernate-core/src/main/java/org/hibernate/boot/model/source/internal/hbm/FetchProfileBinder.java b/hibernate-core/src/main/java/org/hibernate/boot/model/source/internal/hbm/FetchProfileBinder.java index 10bf159f94b7..b8240d41c4ee 100644 --- a/hibernate-core/src/main/java/org/hibernate/boot/model/source/internal/hbm/FetchProfileBinder.java +++ b/hibernate-core/src/main/java/org/hibernate/boot/model/source/internal/hbm/FetchProfileBinder.java @@ -50,7 +50,7 @@ public static void processFetchProfile( String containingEntityName) { FetchProfile profile = context.getMetadataCollector().getFetchProfile( fetchProfileBinding.getName() ); if ( profile == null ) { - log.debugf( "Creating FetchProfile : %s", fetchProfileBinding.getName() ); + log.tracef( "Creating FetchProfile: %s", fetchProfileBinding.getName() ); profile = new FetchProfile( fetchProfileBinding.getName(), MetadataSource.HBM ); context.getMetadataCollector().addFetchProfile( profile ); } diff --git a/hibernate-core/src/main/java/org/hibernate/boot/model/source/internal/hbm/FilterDefinitionBinder.java b/hibernate-core/src/main/java/org/hibernate/boot/model/source/internal/hbm/FilterDefinitionBinder.java index aec3cfeb1ff1..e5a3ed45fade 100644 --- a/hibernate-core/src/main/java/org/hibernate/boot/model/source/internal/hbm/FilterDefinitionBinder.java +++ b/hibernate-core/src/main/java/org/hibernate/boot/model/source/internal/hbm/FilterDefinitionBinder.java @@ -87,6 +87,6 @@ else if ( content instanceof JAXBElement ) { ) ); - log.debugf( "Processed filter definition : %s", jaxbFilterDefinitionMapping.getName() ); + log.tracef( "Processed filter definition: %s", jaxbFilterDefinitionMapping.getName() ); } } diff --git a/hibernate-core/src/main/java/org/hibernate/boot/model/source/internal/hbm/IdentifierGeneratorDefinitionBinder.java b/hibernate-core/src/main/java/org/hibernate/boot/model/source/internal/hbm/IdentifierGeneratorDefinitionBinder.java index fca8551fcac4..2108ceef88ee 100644 --- a/hibernate-core/src/main/java/org/hibernate/boot/model/source/internal/hbm/IdentifierGeneratorDefinitionBinder.java +++ b/hibernate-core/src/main/java/org/hibernate/boot/model/source/internal/hbm/IdentifierGeneratorDefinitionBinder.java @@ -18,7 +18,7 @@ public class IdentifierGeneratorDefinitionBinder { public static void processIdentifierGeneratorDefinition( HbmLocalMetadataBuildingContext context, JaxbHbmIdentifierGeneratorDefinitionType identifierGenerator) { - log.debugf( "Processing : %s", identifierGenerator.getName() ); + log.tracef( "Processing : %s", identifierGenerator.getName() ); context.getMetadataCollector().addIdentifierGenerator( new IdentifierGeneratorDefinition( diff --git a/hibernate-core/src/main/java/org/hibernate/boot/model/source/internal/hbm/MappingDocument.java b/hibernate-core/src/main/java/org/hibernate/boot/model/source/internal/hbm/MappingDocument.java index f575a93beacc..479bebd3307c 100644 --- a/hibernate-core/src/main/java/org/hibernate/boot/model/source/internal/hbm/MappingDocument.java +++ b/hibernate-core/src/main/java/org/hibernate/boot/model/source/internal/hbm/MappingDocument.java @@ -186,7 +186,7 @@ public void processQueryRenames() { ? StringHelper.unqualify( name ) : renameBinding.getRename(); getMetadataCollector().addImport( rename, name ); - log.debugf( "Import (query rename): %s -> %s", rename, name ); + log.tracef( "Import (query rename): %s -> %s", rename, name ); } } diff --git a/hibernate-core/src/main/java/org/hibernate/boot/model/source/internal/hbm/ModelBinder.java b/hibernate-core/src/main/java/org/hibernate/boot/model/source/internal/hbm/ModelBinder.java index 049f3d7745c1..18f2137186ee 100644 --- a/hibernate-core/src/main/java/org/hibernate/boot/model/source/internal/hbm/ModelBinder.java +++ b/hibernate-core/src/main/java/org/hibernate/boot/model/source/internal/hbm/ModelBinder.java @@ -182,8 +182,8 @@ private void bindRootEntity(EntityHierarchySourceImpl hierarchySource, RootClass ); rootEntityDescriptor.setTable( primaryTable ); - if ( log.isDebugEnabled() ) { - log.debugf( "Mapping class: %s -> %s", rootEntityDescriptor.getEntityName(), primaryTable.getName() ); + if ( log.isTraceEnabled() ) { + log.tracef( "Mapping class: %s -> %s", rootEntityDescriptor.getEntityName(), primaryTable.getName() ); } rootEntityDescriptor.setOptimisticLockStyle( hierarchySource.getOptimisticLockStyle() ); @@ -502,8 +502,8 @@ private void bindJoinedSubclassEntity( ); entityDescriptor.setTable( primaryTable ); - if ( log.isDebugEnabled() ) { - log.debugf( "Mapping joined-subclass: %s -> %s", entityDescriptor.getEntityName(), primaryTable.getName() ); + if ( log.isTraceEnabled() ) { + log.tracef( "Mapping joined-subclass: %s -> %s", entityDescriptor.getEntityName(), primaryTable.getName() ); } // KEY @@ -579,8 +579,8 @@ private void bindUnionSubclassEntity( ); entityDescriptor.setTable( primaryTable ); - if ( log.isDebugEnabled() ) { - log.debugf( "Mapping union-subclass: %s -> %s", entityDescriptor.getEntityName(), primaryTable.getName() ); + if ( log.isTraceEnabled() ) { + log.tracef( "Mapping union-subclass: %s -> %s", entityDescriptor.getEntityName(), primaryTable.getName() ); } // todo : tooling hints @@ -1557,8 +1557,8 @@ private void bindSecondaryTable( secondaryTableJoin.setInverse( secondaryTableSource.isInverse() ); secondaryTableJoin.setOptional( secondaryTableSource.isOptional() ); - if ( log.isDebugEnabled() ) { - log.debugf( + if ( log.isTraceEnabled() ) { + log.tracef( "Mapping entity secondary-table: %s -> %s", persistentClass.getEntityName(), secondaryTable.getName() @@ -2335,8 +2335,8 @@ private void bindProperty( property.setMetaAttributes( propertySource.getToolingHintContext().getMetaAttributeMap() ); - if ( log.isDebugEnabled() ) { - log.debug( "Mapped property: " + propertySource.getName() + " -> [" + columns( property.getValue() ) + "]" ); + if ( log.isTraceEnabled() ) { + log.trace( "Mapped property: " + propertySource.getName() + " -> [" + columns( property.getValue() ) + "]" ); } } @@ -2379,8 +2379,8 @@ private static void handleGenerationTiming( // generated properties can *never* be insertable... if ( property.isInsertable() && timing.includesInsert() ) { - log.debugf( - "Property [%s] specified %s generation, setting insertable to false : %s", + log.tracef( + "Property [%s] specified %s generation, setting insertable to false: %s", propertySource.getName(), timing.name(), mappingDocument.getOrigin() @@ -2390,8 +2390,8 @@ private static void handleGenerationTiming( // properties generated on update can never be updatable... if ( property.isUpdateable() && timing.includesUpdate() ) { - log.debugf( - "Property [%s] specified ALWAYS generation, setting updateable to false : %s", + log.tracef( + "Property [%s] specified ALWAYS generation, setting updateable to false: %s", propertySource.getName(), mappingDocument.getOrigin() ); @@ -2454,23 +2454,23 @@ private void bindComponent( // todo : better define the conditions in this if/else if ( isDynamic ) { // dynamic is represented as a Map - log.debugf( "Binding dynamic-component [%s]", role ); + log.tracef( "Binding dynamic-component [%s]", role ); componentBinding.setDynamic( true ); } else if ( isVirtual ) { // virtual (what used to be called embedded) is just a conceptual composition... // for example if ( componentBinding.getOwner().hasPojoRepresentation() ) { - log.debugf( "Binding virtual component [%s] to owner class [%s]", role, componentBinding.getOwner().getClassName() ); + log.tracef( "Binding virtual component [%s] to owner class [%s]", role, componentBinding.getOwner().getClassName() ); componentBinding.setComponentClassName( componentBinding.getOwner().getClassName() ); } else { - log.debugf( "Binding virtual component [%s] as dynamic", role ); + log.tracef( "Binding virtual component [%s] as dynamic", role ); componentBinding.setDynamic( true ); } } else { - log.debugf( "Binding component [%s]", role ); + log.tracef( "Binding component [%s]", role ); if ( isNotEmpty( explicitComponentClassName ) ) { try { final Class componentClass = sourceDocument.getBootstrapContext() @@ -2494,7 +2494,7 @@ else if ( isVirtual ) { catch (ClassLoadingException ex) { log.debugf( ex, "Could load component class [%s]", explicitComponentClassName ); } - log.debugf( "Binding component [%s] to explicitly specified class", role, explicitComponentClassName ); + log.tracef( "Binding component [%s] to explicitly specified class", role, explicitComponentClassName ); componentBinding.setComponentClassName( explicitComponentClassName ); } else if ( componentBinding.getOwner().hasPojoRepresentation() ) { @@ -2982,18 +2982,18 @@ public void doSecondPass(Map persistentClasses) throws collectionBinding.createAllKeys(); - if ( log.isDebugEnabled() ) { - log.debugf( "Mapped collection : %s", getPluralAttributeSource().getAttributeRole().getFullPath() ); - log.debugf( " + table -> %s", getCollectionBinding().getTable().getName() ); - log.debugf( " + key -> %s", columns( getCollectionBinding().getKey() ) ); + if ( log.isTraceEnabled() ) { + log.tracef( "Mapped collection : %s", getPluralAttributeSource().getAttributeRole().getFullPath() ); + log.tracef( " + table -> %s", getCollectionBinding().getTable().getName() ); + log.tracef( " + key -> %s", columns( getCollectionBinding().getKey() ) ); if ( getCollectionBinding().isIndexed() ) { - log.debugf( " + index -> %s", columns( ( (IndexedCollection) getCollectionBinding() ).getIndex() ) ); + log.tracef( " + index -> %s", columns( ( (IndexedCollection) getCollectionBinding() ).getIndex() ) ); } if ( getCollectionBinding().isOneToMany() ) { - log.debugf( " + one-to-many -> %s", ( (OneToMany) getCollectionBinding().getElement() ).getReferencedEntityName() ); + log.tracef( " + one-to-many -> %s", ( (OneToMany) getCollectionBinding().getElement() ).getReferencedEntityName() ); } else { - log.debugf( " + element -> %s", columns( getCollectionBinding().getElement() ) ); + log.tracef( " + element -> %s", columns( getCollectionBinding().getElement() ) ); } } } @@ -3088,8 +3088,10 @@ public MetadataBuildingContext getBuildingContext() { } - if ( log.isDebugEnabled() ) { - log.debugf( "Mapping collection: %s -> %s", collectionBinding.getRole(), collectionBinding.getCollectionTable().getName() ); + if ( log.isTraceEnabled() ) { + log.tracef( "Mapping collection: %s -> %s", + collectionBinding.getRole(), + collectionBinding.getCollectionTable().getName() ); } if ( pluralAttributeSource.getCollectionTableComment() != null ) { @@ -3117,8 +3119,8 @@ protected void createBackReferences() { backref.setValue( collectionBinding.getKey() ); referenced.addProperty( backref ); - if ( log.isDebugEnabled() ) { - log.debugf( + if ( log.isTraceEnabled() ) { + log.tracef( "Added virtual backref property [%s] : %s", backref.getName(), pluralAttributeSource.getAttributeRole().getFullPath() @@ -3208,8 +3210,8 @@ protected void bindCollectionIndex() { protected void bindCollectionElement() { final PluralAttributeElementSource pluralElementSource = getPluralAttributeSource().getElementSource(); - if ( log.isDebugEnabled() ) { - log.debugf( + if ( log.isTraceEnabled() ) { + log.tracef( "Binding [%s] element type for a [%s]", pluralElementSource.getNature(), getPluralAttributeSource().getNature() @@ -3356,8 +3358,8 @@ else if ( pluralElementSource instanceof PluralAttributeElementSourceManyToMany for ( FilterSource filterSource : elementSource.getFilterSources() ) { if ( filterSource.getName() == null ) { - if ( log.isDebugEnabled() ) { - log.debugf( + if ( log.isTraceEnabled() ) { + log.tracef( "Encountered filter with no name associated with many-to-many [%s]; skipping", getPluralAttributeSource().getAttributeRole().getFullPath() ); @@ -3377,8 +3379,8 @@ else if ( pluralElementSource instanceof PluralAttributeElementSourceManyToMany ); } - if ( log.isDebugEnabled() ) { - log.debugf( + if ( log.isTraceEnabled() ) { + log.tracef( "Applying many-to-many filter [%s] as [%s] to collection [%s]", filterSource.getName(), filterSource.getCondition(), @@ -3984,7 +3986,7 @@ public void addAttributeBinding(Property attributeBinding) { @Override public void process() { - log.debugf( "Binding natural-id UniqueKey for entity : %s", entityBinding.getEntityName() ); + log.tracef( "Binding natural-id UniqueKey for entity: %s", entityBinding.getEntityName() ); final List columnNames = new ArrayList<>(); diff --git a/hibernate-core/src/main/java/org/hibernate/boot/model/source/internal/hbm/TypeDefinitionBinder.java b/hibernate-core/src/main/java/org/hibernate/boot/model/source/internal/hbm/TypeDefinitionBinder.java index bf49aeb9ac3f..ed52b61e7464 100644 --- a/hibernate-core/src/main/java/org/hibernate/boot/model/source/internal/hbm/TypeDefinitionBinder.java +++ b/hibernate-core/src/main/java/org/hibernate/boot/model/source/internal/hbm/TypeDefinitionBinder.java @@ -33,8 +33,8 @@ public static void processTypeDefinition( ConfigParameterHelper.extractConfigParameters( typeDefinitionBinding ) ); - if ( log.isDebugEnabled() ) { - log.debugf( + if ( log.isTraceEnabled() ) { + log.tracef( "Processed type-definition : %s -> %s", definition.getName(), definition.getTypeImplementorClass().getName() diff --git a/hibernate-core/src/main/java/org/hibernate/boot/models/xml/internal/ManagedTypeProcessor.java b/hibernate-core/src/main/java/org/hibernate/boot/models/xml/internal/ManagedTypeProcessor.java index 122f7b5973dc..c9d19eb7688d 100644 --- a/hibernate-core/src/main/java/org/hibernate/boot/models/xml/internal/ManagedTypeProcessor.java +++ b/hibernate-core/src/main/java/org/hibernate/boot/models/xml/internal/ManagedTypeProcessor.java @@ -313,7 +313,9 @@ private static void renderClass(MutableClassDetails classDetails, XmlDocumentCon final RenderingTargetCollectingImpl collectingTarget = new RenderingTargetCollectingImpl(); final SimpleRenderer renderer = new SimpleRenderer( collectingTarget ); renderer.renderClass( classDetails, xmlDocumentContext.getModelBuildingContext() ); - XML_PROCESS_LOGGER.debugf( "Class annotations from XML for %s:\n%s", classDetails.getName(), collectingTarget.toString() ); + XML_PROCESS_LOGGER.tracef( "Class annotations from XML for %s:\n%s", + classDetails.getName(), + collectingTarget.toString() ); } private static void applyAccessAnnotation( diff --git a/hibernate-core/src/main/java/org/hibernate/boot/models/xml/internal/PersistenceUnitMetadataImpl.java b/hibernate-core/src/main/java/org/hibernate/boot/models/xml/internal/PersistenceUnitMetadataImpl.java index 13084161636d..fc016ec0889b 100644 --- a/hibernate-core/src/main/java/org/hibernate/boot/models/xml/internal/PersistenceUnitMetadataImpl.java +++ b/hibernate-core/src/main/java/org/hibernate/boot/models/xml/internal/PersistenceUnitMetadataImpl.java @@ -89,8 +89,8 @@ public void apply(JaxbPersistenceUnitMetadataImpl metadata) { if ( isNotEmpty( defaults.getCatalog() ) ) { if ( defaultCatalog != null ) { - XML_PROCESS_LOGGER.debugf( - "Setting already set default catalog : %s, %s", + XML_PROCESS_LOGGER.tracef( + "Setting already set default catalog: %s, %s", defaultCatalog, defaults.getCatalog() ); @@ -100,8 +100,8 @@ public void apply(JaxbPersistenceUnitMetadataImpl metadata) { if ( isNotEmpty( defaults.getSchema() ) ) { if ( defaultSchema != null ) { - XML_PROCESS_LOGGER.debugf( - "Setting already set default schema : %s, %s", + XML_PROCESS_LOGGER.tracef( + "Setting already set default schema: %s, %s", defaultSchema, defaults.getSchema() ); @@ -111,8 +111,8 @@ public void apply(JaxbPersistenceUnitMetadataImpl metadata) { if ( defaults.getAccess() != null ) { if ( accessType != null ) { - XML_PROCESS_LOGGER.debugf( - "Overriding already set default AccessType : %s, %s", + XML_PROCESS_LOGGER.tracef( + "Overriding already set default AccessType: %s, %s", defaults.getAccess(), accessType ); @@ -122,8 +122,8 @@ public void apply(JaxbPersistenceUnitMetadataImpl metadata) { if ( isNotEmpty( defaults.getDefaultAccess() ) ) { if ( defaultAccessStrategy != null ) { - XML_PROCESS_LOGGER.debugf( - "Overriding already set default access strategy : %s, %s", + XML_PROCESS_LOGGER.tracef( + "Overriding already set default access strategy: %s, %s", accessType, defaultAccessStrategy ); @@ -133,8 +133,8 @@ public void apply(JaxbPersistenceUnitMetadataImpl metadata) { if ( defaults.getCascadePersist() != null || isNotEmpty( defaults.getDefaultCascade() ) ) { - if ( !this.defaultCascadeTypes.isEmpty() ) { - XML_PROCESS_LOGGER.debugf( "Adding cascades to already defined set of default cascades" ); + if ( !defaultCascadeTypes.isEmpty() ) { + XML_PROCESS_LOGGER.tracef( "Adding cascades to already defined set of default cascades" ); } if ( defaults.getCascadePersist() != null ) { diff --git a/hibernate-core/src/main/java/org/hibernate/boot/query/HbmResultSetMappingDescriptor.java b/hibernate-core/src/main/java/org/hibernate/boot/query/HbmResultSetMappingDescriptor.java index a97806a7b293..f89921cb4ac3 100644 --- a/hibernate-core/src/main/java/org/hibernate/boot/query/HbmResultSetMappingDescriptor.java +++ b/hibernate-core/src/main/java/org/hibernate/boot/query/HbmResultSetMappingDescriptor.java @@ -7,7 +7,6 @@ import org.hibernate.AssertionFailure; import org.hibernate.LockMode; import org.hibernate.MappingException; -import org.hibernate.boot.BootLogging; import org.hibernate.boot.jaxb.hbm.spi.JaxbHbmNativeQueryCollectionLoadReturnType; import org.hibernate.boot.jaxb.hbm.spi.JaxbHbmNativeQueryJoinReturnType; import org.hibernate.boot.jaxb.hbm.spi.JaxbHbmNativeQueryPropertyReturnType; @@ -63,6 +62,7 @@ import java.util.StringTokenizer; import java.util.function.Supplier; +import static org.hibernate.boot.BootLogging.BOOT_LOGGER; import static org.hibernate.internal.util.StringHelper.split; /** @@ -87,8 +87,8 @@ public HbmResultSetMappingDescriptor( MetadataBuildingContext context) { this.registrationName = hbmResultSetMapping.getName(); - BootLogging.BOOT_LOGGER.debugf( - "Creating explicit HbmResultSetMappingDescriptor : %s", + BOOT_LOGGER.tracef( + "Creating explicit HbmResultSetMappingDescriptor: %s", registrationName ); @@ -254,7 +254,7 @@ public String getRegistrationName() { @Override public NamedResultSetMappingMemento resolve(ResultSetMappingResolutionContext resolutionContext) { - BootQueryLogging.BOOT_QUERY_LOGGER.debugf( + BootQueryLogging.BOOT_QUERY_LOGGER.tracef( "Resolving HbmResultSetMappingDescriptor into memento for [%s]", registrationName ); @@ -343,7 +343,7 @@ public EntityResultDescriptor( ); } - BootQueryLogging.BOOT_QUERY_LOGGER.debugf( + BootQueryLogging.BOOT_QUERY_LOGGER.tracef( "Creating EntityResultDescriptor (%s : %s) for ResultSet mapping - %s", tableAlias, entityName, @@ -367,7 +367,7 @@ public EntityResultDescriptor( @Override public ResultMemento resolve(ResultSetMappingResolutionContext resolutionContext) { - BootQueryLogging.BOOT_QUERY_LOGGER.debugf( + BootQueryLogging.BOOT_QUERY_LOGGER.tracef( "Resolving HBM EntityResultDescriptor into memento - %s : %s (%s)", tableAlias, entityName, @@ -517,7 +517,7 @@ public PropertyFetchDescriptor( } } - BootQueryLogging.BOOT_QUERY_LOGGER.debugf( + BootQueryLogging.BOOT_QUERY_LOGGER.tracef( "Creating PropertyFetchDescriptor (%s : %s) for ResultSet mapping - %s", parent, propertyPath, @@ -637,7 +637,7 @@ private static List extractColumnAliases(JaxbHbmNativeQueryPropertyRetur @Override public FetchMemento resolve(ResultSetMappingResolutionContext resolutionContext) { - BootQueryLogging.BOOT_QUERY_LOGGER.debugf( + BootQueryLogging.BOOT_QUERY_LOGGER.tracef( "Resolving HBM PropertyFetchDescriptor into memento - %s : %s", parent, propertyPath @@ -756,7 +756,7 @@ public String getFetchablePath() { @Override public FetchMemento resolve(ResultSetMappingResolutionContext resolutionContext) { - BootQueryLogging.BOOT_QUERY_LOGGER.debugf( + BootQueryLogging.BOOT_QUERY_LOGGER.tracef( "Resolving HBM JoinDescriptor into memento - %s : %s . %s", tableAlias, ownerTableAlias, @@ -872,7 +872,7 @@ public CollectionResultDescriptor( ); } - BootQueryLogging.BOOT_QUERY_LOGGER.debugf( + BootQueryLogging.BOOT_QUERY_LOGGER.tracef( "Creating CollectionResultDescriptor (%s : %s)", tableAlias, collectionPath @@ -894,7 +894,7 @@ public CollectionResultDescriptor( @Override public ResultMemento resolve(ResultSetMappingResolutionContext resolutionContext) { - BootQueryLogging.BOOT_QUERY_LOGGER.debugf( + BootQueryLogging.BOOT_QUERY_LOGGER.tracef( "Resolving HBM CollectionResultDescriptor into memento - %s : %s", tableAlias, collectionPath @@ -940,7 +940,7 @@ public ScalarDescriptor(String columnName, String hibernateTypeName) { this.columnName = columnName; this.hibernateTypeName = hibernateTypeName; - BootQueryLogging.BOOT_QUERY_LOGGER.debugf( + BootQueryLogging.BOOT_QUERY_LOGGER.tracef( "Creating ScalarDescriptor (%s)", columnName ); @@ -952,7 +952,7 @@ public ScalarDescriptor(JaxbHbmNativeQueryScalarReturnType hbmScalarReturn) { @Override public ResultMementoBasicStandard resolve(ResultSetMappingResolutionContext resolutionContext) { - BootQueryLogging.BOOT_QUERY_LOGGER.debugf( + BootQueryLogging.BOOT_QUERY_LOGGER.tracef( "Resolving HBM ScalarDescriptor into memento - %s", columnName ); diff --git a/hibernate-core/src/main/java/org/hibernate/boot/query/ImplicitHbmResultSetMappingDescriptorBuilder.java b/hibernate-core/src/main/java/org/hibernate/boot/query/ImplicitHbmResultSetMappingDescriptorBuilder.java index 459a02787076..8fa75eed27c2 100644 --- a/hibernate-core/src/main/java/org/hibernate/boot/query/ImplicitHbmResultSetMappingDescriptorBuilder.java +++ b/hibernate-core/src/main/java/org/hibernate/boot/query/ImplicitHbmResultSetMappingDescriptorBuilder.java @@ -20,6 +20,7 @@ import org.hibernate.boot.query.HbmResultSetMappingDescriptor.JoinDescriptor; import org.hibernate.boot.spi.MetadataBuildingContext; +import static org.hibernate.boot.query.BootQueryLogging.BOOT_QUERY_LOGGER; import static org.hibernate.boot.query.HbmResultSetMappingDescriptor.*; /** @@ -44,7 +45,7 @@ public class ImplicitHbmResultSetMappingDescriptorBuilder { public ImplicitHbmResultSetMappingDescriptorBuilder(String queryRegistrationName, MetadataBuildingContext metadataBuildingContext) { this.registrationName = queryRegistrationName; - BootQueryLogging.BOOT_QUERY_LOGGER.debugf( + BOOT_QUERY_LOGGER.tracef( "Creating implicit HbmResultSetMappingDescriptor for named-native-query : %s", registrationName ); diff --git a/hibernate-core/src/main/java/org/hibernate/boot/query/SqlResultSetMappingDescriptor.java b/hibernate-core/src/main/java/org/hibernate/boot/query/SqlResultSetMappingDescriptor.java index 47da3473b41b..d7effab54989 100644 --- a/hibernate-core/src/main/java/org/hibernate/boot/query/SqlResultSetMappingDescriptor.java +++ b/hibernate-core/src/main/java/org/hibernate/boot/query/SqlResultSetMappingDescriptor.java @@ -45,6 +45,7 @@ import jakarta.persistence.LockModeType; import jakarta.persistence.SqlResultSetMapping; +import static org.hibernate.boot.query.BootQueryLogging.BOOT_QUERY_LOGGER; import static org.hibernate.internal.util.collections.CollectionHelper.arrayList; import static org.hibernate.internal.util.collections.CollectionHelper.mapOfSize; import static org.hibernate.metamodel.mapping.EntityIdentifierMapping.ID_ROLE_NAME; @@ -139,7 +140,7 @@ public JpaColumnResultDescriptor( @Override public ResultMemento resolve(ResultSetMappingResolutionContext resolutionContext) { - BootQueryLogging.BOOT_QUERY_LOGGER.debugf( + BOOT_QUERY_LOGGER.tracef( "Generating ScalarResultMappingMemento for JPA ColumnResult(%s) for ResultSet mapping `%s`", columnResult.name(), mappingName @@ -200,7 +201,7 @@ private static List interpretArguments( @Override public ResultMemento resolve(ResultSetMappingResolutionContext resolutionContext) { - BootQueryLogging.BOOT_QUERY_LOGGER.debugf( + BOOT_QUERY_LOGGER.tracef( "Generating InstantiationResultMappingMemento for JPA ConstructorResult(%s) for ResultSet mapping `%s`", targetJavaType.getName(), mappingName diff --git a/hibernate-core/src/main/java/org/hibernate/boot/registry/internal/BootstrapServiceRegistryImpl.java b/hibernate-core/src/main/java/org/hibernate/boot/registry/internal/BootstrapServiceRegistryImpl.java index e9f148b8b6c7..e9e18dcdcd26 100644 --- a/hibernate-core/src/main/java/org/hibernate/boot/registry/internal/BootstrapServiceRegistryImpl.java +++ b/hibernate-core/src/main/java/org/hibernate/boot/registry/internal/BootstrapServiceRegistryImpl.java @@ -292,17 +292,11 @@ public synchronized void deRegisterChild(ServiceRegistryImplementor child) { childRegistries.remove( child ); if ( childRegistries.isEmpty() ) { if ( autoCloseRegistry ) { - LOG.debug( - "Implicitly destroying Boot-strap registry on de-registration " + - "of all child ServiceRegistries" - ); + LOG.trace( "Implicitly destroying Bootstrap registry on deregistration of all child ServiceRegistries" ); destroy(); } else { - LOG.debug( - "Skipping implicitly destroying Boot-strap registry on de-registration " + - "of all child ServiceRegistries" - ); + LOG.trace( "Skipping implicitly destroying Bootstrap registry on deregistration of all child ServiceRegistries" ); } } } diff --git a/hibernate-core/src/main/java/org/hibernate/boot/registry/selector/internal/StrategySelectorBuilder.java b/hibernate-core/src/main/java/org/hibernate/boot/registry/selector/internal/StrategySelectorBuilder.java index af0eda071fda..84ed7df99401 100644 --- a/hibernate-core/src/main/java/org/hibernate/boot/registry/selector/internal/StrategySelectorBuilder.java +++ b/hibernate-core/src/main/java/org/hibernate/boot/registry/selector/internal/StrategySelectorBuilder.java @@ -87,8 +87,8 @@ public void addExplicitStrategyRegistration(Class strategy, Class void addExplicitStrategyRegistration(StrategyRegistration strategyRegistration) { if ( !strategyRegistration.getStrategyRole().isInterface() ) { // not good form... - if ( log.isDebugEnabled() ) { - log.debugf( "Registering non-interface strategy : %s", strategyRegistration.getStrategyRole().getName() ); + if ( log.isTraceEnabled() ) { + log.tracef( "Registering non-interface strategy : %s", strategyRegistration.getStrategyRole().getName() ); } } diff --git a/hibernate-core/src/main/java/org/hibernate/boot/registry/selector/internal/StrategySelectorImpl.java b/hibernate-core/src/main/java/org/hibernate/boot/registry/selector/internal/StrategySelectorImpl.java index 3a8183d52013..fa39cda3ed40 100644 --- a/hibernate-core/src/main/java/org/hibernate/boot/registry/selector/internal/StrategySelectorImpl.java +++ b/hibernate-core/src/main/java/org/hibernate/boot/registry/selector/internal/StrategySelectorImpl.java @@ -196,14 +196,10 @@ public void registerStrategyLazily(Class strategy, LazyServiceResolver } private void contributeImplementation(Class strategy, Class implementation, String... names) { - final Map> namedStrategyImplementorMap = namedStrategyImplementorByStrategyMap.computeIfAbsent( - strategy, - aClass -> new ConcurrentHashMap<>() - ); - - for ( int i = 0; i < names.length; i++ ) { - final String name = names[i]; + final var namedStrategyImplementorMap = + namedStrategyImplementorByStrategyMap.computeIfAbsent( strategy, clazz -> new ConcurrentHashMap<>() ); + for ( String name : names ) { final Class old = namedStrategyImplementorMap.put( name, implementation ); if ( old == null ) { if ( log.isTraceEnabled() ) { @@ -218,8 +214,8 @@ private void contributeImplementation(Class strategy, Class } } else { - if ( log.isDebugEnabled() ) { - log.debug( + if ( log.isTraceEnabled() ) { + log.trace( String.format( "Registering named strategy selector [%s] : [%s] -> [%s] (replacing [%s])", strategy.getName(), @@ -236,7 +232,7 @@ private void contributeImplementation(Class strategy, Class private void removeImplementation(Class strategy, Class implementation) { final Map> namedStrategyImplementorMap = namedStrategyImplementorByStrategyMap.get( strategy ); if ( namedStrategyImplementorMap == null ) { - log.debug( "Named strategy map did not exist on call to un-register" ); + log.debug( "Named strategy map did not exist on call to unregister" ); return; } diff --git a/hibernate-core/src/main/java/org/hibernate/boot/spi/XmlMappingBinderAccess.java b/hibernate-core/src/main/java/org/hibernate/boot/spi/XmlMappingBinderAccess.java index 023f85b73ad0..da2a703ab9e5 100644 --- a/hibernate-core/src/main/java/org/hibernate/boot/spi/XmlMappingBinderAccess.java +++ b/hibernate-core/src/main/java/org/hibernate/boot/spi/XmlMappingBinderAccess.java @@ -111,7 +111,7 @@ public Binding bind(InputStream xmlInputStream) { */ public Binding bind(URL url) { final String urlExternalForm = url.toExternalForm(); - LOG.debugf( "Reading mapping document from URL : %s", urlExternalForm ); + LOG.tracef( "Reading mapping document from URL: %s", urlExternalForm ); final Origin origin = new Origin( SourceType.URL, urlExternalForm ); return new UrlXmlSource( origin, url ).doBind( getMappingBinder() ); } diff --git a/hibernate-core/src/main/java/org/hibernate/boot/xsd/LocalXsdResolver.java b/hibernate-core/src/main/java/org/hibernate/boot/xsd/LocalXsdResolver.java index b0a04b550ca7..61c0f1f75d16 100644 --- a/hibernate-core/src/main/java/org/hibernate/boot/xsd/LocalXsdResolver.java +++ b/hibernate-core/src/main/java/org/hibernate/boot/xsd/LocalXsdResolver.java @@ -101,7 +101,8 @@ public static Schema resolveLocalXsdSchema(String schemaResourceName) { schemaStream.close(); } catch ( IOException e ) { - Logger.getLogger( LocalXsdResolver.class ).debugf( "Problem closing schema stream [%s]", e.toString() ); + Logger.getLogger( LocalXsdResolver.class ) + .debugf( "Problem closing schema stream [%s]", e.toString() ); } } } diff --git a/hibernate-core/src/main/java/org/hibernate/bytecode/enhance/internal/bytebuddy/BiDirectionalAssociationHandler.java b/hibernate-core/src/main/java/org/hibernate/bytecode/enhance/internal/bytebuddy/BiDirectionalAssociationHandler.java index 30417eba8bf2..a3aa90e30f46 100644 --- a/hibernate-core/src/main/java/org/hibernate/bytecode/enhance/internal/bytebuddy/BiDirectionalAssociationHandler.java +++ b/hibernate-core/src/main/java/org/hibernate/bytecode/enhance/internal/bytebuddy/BiDirectionalAssociationHandler.java @@ -253,8 +253,8 @@ private static String getMappedByManyToMany(AnnotatedFieldDescription target, Ty if ( context.isPersistentField( annotatedF ) && target.getName().equals( getMappedBy( annotatedF, entityType( annotatedF.getType() ), context ) ) && target.getDeclaringType().asErasure().isAssignableTo( entityType( annotatedF.getType() ) ) ) { - if ( log.isDebugEnabled() ) { - log.debugf( + if ( log.isTraceEnabled() ) { + log.tracef( "mappedBy association for field [%s#%s] is [%s#%s]", target.getDeclaringType().asErasure().getName(), target.getName(), diff --git a/hibernate-core/src/main/java/org/hibernate/bytecode/enhance/internal/bytebuddy/EnhancerImpl.java b/hibernate-core/src/main/java/org/hibernate/bytecode/enhance/internal/bytebuddy/EnhancerImpl.java index 483789ec1d23..211d192dd442 100644 --- a/hibernate-core/src/main/java/org/hibernate/bytecode/enhance/internal/bytebuddy/EnhancerImpl.java +++ b/hibernate-core/src/main/java/org/hibernate/bytecode/enhance/internal/bytebuddy/EnhancerImpl.java @@ -175,19 +175,19 @@ private DynamicType.Builder doEnhance(Supplier> builde // I'm currently inclined to keep both checks, as one is safer and the other has better backwards compatibility. if ( managedCtClass.getDeclaredAnnotations().isAnnotationPresent( EnhancementInfo.class ) ) { verifyVersions( managedCtClass, enhancementContext ); - log.debugf( "Skipping enhancement of [%s]: it's already annotated with @EnhancementInfo", managedCtClass.getName() ); + log.tracef( "Skipping enhancement of [%s]: it's already annotated with @EnhancementInfo", managedCtClass.getName() ); return null; } // can't effectively enhance interfaces if ( managedCtClass.isInterface() ) { - log.debugf( "Skipping enhancement of [%s]: it's an interface", managedCtClass.getName() ); + log.tracef( "Skipping enhancement of [%s]: it's an interface", managedCtClass.getName() ); return null; } // can't effectively enhance records if ( managedCtClass.isRecord() ) { - log.debugf( "Skipping enhancement of [%s]: it's a record", managedCtClass.getName() ); + log.tracef( "Skipping enhancement of [%s]: it's a record", managedCtClass.getName() ); return null; } @@ -195,7 +195,7 @@ private DynamicType.Builder doEnhance(Supplier> builde if ( alreadyEnhanced( managedCtClass ) ) { verifyVersions( managedCtClass, enhancementContext ); - log.debugf( "Skipping enhancement of [%s]: it's already implementing 'Managed'", managedCtClass.getName() ); + log.tracef( "Skipping enhancement of [%s]: it's already implementing 'Managed'", managedCtClass.getName() ); return null; } @@ -205,7 +205,7 @@ private DynamicType.Builder doEnhance(Supplier> builde return null; } - log.debugf( "Enhancing [%s] as Entity", managedCtClass.getName() ); + log.tracef( "Enhancing [%s] as Entity", managedCtClass.getName() ); DynamicType.Builder builder = builderSupplier.get(); builder = builder.implement( ManagedEntity.class ) .defineMethod( EnhancerConstants.ENTITY_INSTANCE_GETTER_NAME, constants.TypeObject, constants.methodModifierPUBLIC ) @@ -384,7 +384,7 @@ else if ( enhancementContext.isCompositeClass( managedCtClass ) ) { return null; } - log.debugf( "Enhancing [%s] as Composite", managedCtClass.getName() ); + log.tracef( "Enhancing [%s] as Composite", managedCtClass.getName() ); DynamicType.Builder builder = builderSupplier.get(); builder = builder.implement( ManagedComposite.class ); @@ -422,18 +422,18 @@ else if ( enhancementContext.isMappedSuperclassClass( managedCtClass ) ) { return null; } - log.debugf( "Enhancing [%s] as MappedSuperclass", managedCtClass.getName() ); + log.tracef( "Enhancing [%s] as MappedSuperclass", managedCtClass.getName() ); DynamicType.Builder builder = builderSupplier.get(); builder = builder.implement( ManagedMappedSuperclass.class ); return createTransformer( managedCtClass ).applyTo( builder ); } else if ( enhancementContext.doExtendedEnhancement( managedCtClass ) ) { - log.debugf( "Extended enhancement of [%s]", managedCtClass.getName() ); + log.tracef( "Extended enhancement of [%s]", managedCtClass.getName() ); return createTransformer( managedCtClass ).applyExtended( builderSupplier.get() ); } else { - log.debugf( "Skipping enhancement of [%s]: not entity or composite", managedCtClass.getName() ); + log.tracef( "Skipping enhancement of [%s]: not entity or composite", managedCtClass.getName() ); return null; } } @@ -671,7 +671,7 @@ private boolean alreadyEnhanced(TypeDescription managedCtClass) { private DynamicType.Builder addInterceptorHandling(DynamicType.Builder builder, TypeDescription managedCtClass) { // interceptor handling is only needed if class has lazy-loadable attributes if ( enhancementContext.hasLazyLoadableAttributes( managedCtClass ) ) { - log.debugf( "Weaving in PersistentAttributeInterceptable implementation on [%s]", managedCtClass.getName() ); + log.tracef( "Weaving in PersistentAttributeInterceptable implementation on [%s]", managedCtClass.getName() ); builder = builder.implement( PersistentAttributeInterceptable.class ); diff --git a/hibernate-core/src/main/java/org/hibernate/bytecode/enhance/internal/bytebuddy/FieldAccessEnhancer.java b/hibernate-core/src/main/java/org/hibernate/bytecode/enhance/internal/bytebuddy/FieldAccessEnhancer.java index 7eeeba095282..6f03d2b44ae0 100644 --- a/hibernate-core/src/main/java/org/hibernate/bytecode/enhance/internal/bytebuddy/FieldAccessEnhancer.java +++ b/hibernate-core/src/main/java/org/hibernate/bytecode/enhance/internal/bytebuddy/FieldAccessEnhancer.java @@ -76,7 +76,7 @@ public void visitFieldInsn(int opcode, String owner, String name, String desc) { && !field.hasAnnotation( Id.class ) && !field.getName().equals( "this$0" ) ) { - log.debugf( + log.tracef( "Extended enhancement: Transforming access to field [%s#%s] from method [%s#%s()]", declaredOwnerType.getName(), field.getName(), diff --git a/hibernate-core/src/main/java/org/hibernate/bytecode/enhance/internal/bytebuddy/PersistentAttributeTransformer.java b/hibernate-core/src/main/java/org/hibernate/bytecode/enhance/internal/bytebuddy/PersistentAttributeTransformer.java index a28d4bfab8f6..eae0f72b5264 100644 --- a/hibernate-core/src/main/java/org/hibernate/bytecode/enhance/internal/bytebuddy/PersistentAttributeTransformer.java +++ b/hibernate-core/src/main/java/org/hibernate/bytecode/enhance/internal/bytebuddy/PersistentAttributeTransformer.java @@ -127,8 +127,8 @@ public static PersistentAttributeTransformer collectPersistentFields( } AnnotatedFieldDescription[] orderedFields = enhancementContext.order( persistentFieldList.toArray( new AnnotatedFieldDescription[0] ) ); - if ( log.isDebugEnabled() ) { - log.debugf( + if ( log.isTraceEnabled() ) { + log.tracef( "Persistent fields for entity %s: %s", managedCtClass.getName(), Arrays.toString( orderedFields ) @@ -155,7 +155,7 @@ else if ( !enhancementContext.isMappedSuperclassClass( managedCtSuperclass.asEra return collectInheritPersistentFields( managedCtSuperclass, enhancementContext ); } - log.debugf( "Found @MappedSuperclass %s to collectPersistenceFields", managedCtSuperclass ); + log.tracef( "Found @MappedSuperclass %s to collectPersistenceFields", managedCtSuperclass ); List persistentFieldList = new ArrayList<>(); diff --git a/hibernate-core/src/main/java/org/hibernate/cache/internal/CollectionCacheInvalidator.java b/hibernate-core/src/main/java/org/hibernate/cache/internal/CollectionCacheInvalidator.java index 97196d30e196..7f2c5155d270 100644 --- a/hibernate-core/src/main/java/org/hibernate/cache/internal/CollectionCacheInvalidator.java +++ b/hibernate-core/src/main/java/org/hibernate/cache/internal/CollectionCacheInvalidator.java @@ -127,8 +127,8 @@ private void evictCollection( handleInverseOneToMany( entity, persister, oldState, collectionPersister, session ); } else { - if ( LOG.isDebugEnabled() ) { - LOG.debug( "Evict CollectionRegion " + collectionPersister.getRole() ); + if ( LOG.isTraceEnabled() ) { + LOG.trace( "Evict CollectionRegion " + collectionPersister.getRole() ); } final CollectionDataAccess cacheAccessStrategy = collectionPersister.getCacheAccessStrategy(); final SoftLock softLock = cacheAccessStrategy.lockRegion(); @@ -184,8 +184,8 @@ private Object getIdentifier(SharedSessionContractImplementor session, Object ob } private void evict(Object id, CollectionPersister collectionPersister, EventSource session) { - if ( LOG.isDebugEnabled() ) { - LOG.debug( "Evict CollectionRegion " + collectionPersister.getRole() + " for id " + id ); + if ( LOG.isTraceEnabled() ) { + LOG.trace( "Evict CollectionRegion " + collectionPersister.getRole() + " for id " + id ); } final CollectionEvictCacheAction evictCacheAction = new CollectionEvictCacheAction( collectionPersister, null, id, session ); diff --git a/hibernate-core/src/main/java/org/hibernate/cache/internal/EnabledCaching.java b/hibernate-core/src/main/java/org/hibernate/cache/internal/EnabledCaching.java index 10c6addb3b34..da7c98f010a8 100644 --- a/hibernate-core/src/main/java/org/hibernate/cache/internal/EnabledCaching.java +++ b/hibernate-core/src/main/java/org/hibernate/cache/internal/EnabledCaching.java @@ -259,8 +259,8 @@ public void evictEntityData(String entityName, Object identifier) { final EntityPersister persister = getEntityDescriptor( entityName ); final EntityDataAccess cacheAccess = persister.getCacheAccessStrategy(); if ( cacheAccess != null ) { - if ( LOG.isDebugEnabled() ) { - LOG.debug( "Evicting entity second-level cache: " + if ( LOG.isTraceEnabled() ) { + LOG.trace( "Evicting entity second-level cache: " + infoString( persister, identifier, sessionFactory ) ); } @@ -305,8 +305,8 @@ protected void evictEntityData(EntityPersister entityDescriptor) { private void evictEntityData(NavigableRole navigableRole, EntityDataAccess cacheAccess) { if ( cacheAccess != null ) { - if ( LOG.isDebugEnabled() ) { - LOG.debug( "Evicting entity second-level cache: " + navigableRole.getFullPath() ); + if ( LOG.isTraceEnabled() ) { + LOG.trace( "Evicting entity second-level cache: " + navigableRole.getFullPath() ); } cacheAccess.evictAll(); } @@ -344,8 +344,8 @@ public void evictNaturalIdData() { private void evictNaturalIdData(NavigableRole rootEntityRole, NaturalIdDataAccess cacheAccess) { if ( cacheAccess != null ) { - if ( LOG.isDebugEnabled() ) { - LOG.debug( "Evicting natural-id cache: " + rootEntityRole.getFullPath() ); + if ( LOG.isTraceEnabled() ) { + LOG.trace( "Evicting natural-id cache: " + rootEntityRole.getFullPath() ); } cacheAccess.evictAll(); } @@ -375,8 +375,8 @@ public void evictCollectionData(String role, Object ownerIdentifier) { final CollectionPersister persister = getCollectionDescriptor( role ); final CollectionDataAccess cacheAccess = persister.getCacheAccessStrategy(); if ( cacheAccess != null ) { - if ( LOG.isDebugEnabled() ) { - LOG.debug( "Evicting collection second-level cache: " + if ( LOG.isTraceEnabled() ) { + LOG.trace( "Evicting collection second-level cache: " + collectionInfoString( persister, ownerIdentifier, sessionFactory ) ); } @@ -398,8 +398,8 @@ private void evictCollectionData(CollectionPersister collectionDescriptor) { private void evictCollectionData(NavigableRole navigableRole, CollectionDataAccess cacheAccess) { if ( cacheAccess != null ) { - if ( LOG.isDebugEnabled() ) { - LOG.debug( "Evicting collection second-level cache: " + navigableRole.getFullPath() ); + if ( LOG.isTraceEnabled() ) { + LOG.trace( "Evicting collection second-level cache: " + navigableRole.getFullPath() ); } cacheAccess.evictAll(); } @@ -435,8 +435,8 @@ public void evictQueryRegion(String regionName) { private void evictQueryResultRegion(QueryResultsCache cache) { if ( cache != null ) { - if ( LOG.isDebugEnabled() ) { - LOG.debug( "Evicting query cache region: " + cache.getRegion().getName() ); + if ( LOG.isTraceEnabled() ) { + LOG.trace( "Evicting query cache region: " + cache.getRegion().getName() ); } cache.clear(); } @@ -444,8 +444,8 @@ private void evictQueryResultRegion(QueryResultsCache cache) { @Override public void evictQueryRegions() { - if ( LOG.isDebugEnabled() ) { - LOG.debug( "Evicting cache of all query regions" ); + if ( LOG.isTraceEnabled() ) { + LOG.trace( "Evicting cache of all query regions" ); } evictQueryResultRegion( defaultQueryResultsCache ); diff --git a/hibernate-core/src/main/java/org/hibernate/cache/internal/QueryResultsCacheImpl.java b/hibernate-core/src/main/java/org/hibernate/cache/internal/QueryResultsCacheImpl.java index f228ffdf4bd4..02a437fa8f4b 100644 --- a/hibernate-core/src/main/java/org/hibernate/cache/internal/QueryResultsCacheImpl.java +++ b/hibernate-core/src/main/java/org/hibernate/cache/internal/QueryResultsCacheImpl.java @@ -50,8 +50,8 @@ public boolean put( final QueryKey key, final List results, final SharedSessionContractImplementor session) throws HibernateException { - if ( L2CACHE_LOGGER.isDebugEnabled() ) { - L2CACHE_LOGGER.debugf( "Caching query results in region: %s; timestamp=%s", + if ( L2CACHE_LOGGER.isTraceEnabled() ) { + L2CACHE_LOGGER.tracef( "Caching query results in region: %s; timestamp=%s", cacheRegion.getName(), session.getCacheTransactionSynchronization().getCachingTimestamp() ); } @@ -90,28 +90,28 @@ public List get( final QueryKey key, final Set spaces, final SharedSessionContractImplementor session) throws HibernateException { - final boolean loggerDebugEnabled = L2CACHE_LOGGER.isDebugEnabled(); - if ( loggerDebugEnabled ) { - L2CACHE_LOGGER.debugf( "Checking cached query results in region: %s", cacheRegion.getName() ); + final boolean loggerTraceEnabled = L2CACHE_LOGGER.isTraceEnabled(); + if ( loggerTraceEnabled ) { + L2CACHE_LOGGER.tracef( "Checking cached query results in region: %s", cacheRegion.getName() ); } final CacheItem cacheItem = getCachedData( key, session ); if ( cacheItem == null ) { - if ( loggerDebugEnabled ) { - L2CACHE_LOGGER.debug( "Query results were not found in cache" ); + if ( loggerTraceEnabled ) { + L2CACHE_LOGGER.trace( "Query results were not found in cache" ); } return null; } if ( !timestampsCache.isUpToDate( spaces, cacheItem.timestamp, session ) ) { - if ( loggerDebugEnabled ) { - L2CACHE_LOGGER.debug( "Cached query results were not up-to-date" ); + if ( loggerTraceEnabled ) { + L2CACHE_LOGGER.trace( "Cached query results were not up-to-date" ); } return null; } - if ( loggerDebugEnabled ) { - L2CACHE_LOGGER.debug( "Returning cached query results" ); + if ( loggerTraceEnabled ) { + L2CACHE_LOGGER.trace( "Returning cached query results" ); } // No need to copy results, since consumers will never mutate @@ -123,28 +123,28 @@ public List get( final QueryKey key, final String[] spaces, final SharedSessionContractImplementor session) throws HibernateException { - final boolean loggerDebugEnabled = L2CACHE_LOGGER.isDebugEnabled(); - if ( loggerDebugEnabled ) { - L2CACHE_LOGGER.debugf( "Checking cached query results in region: %s", cacheRegion.getName() ); + final boolean loggerTraceEnabled = L2CACHE_LOGGER.isTraceEnabled(); + if ( loggerTraceEnabled ) { + L2CACHE_LOGGER.tracef( "Checking cached query results in region: %s", cacheRegion.getName() ); } final CacheItem cacheItem = getCachedData( key, session ); if ( cacheItem == null ) { - if ( loggerDebugEnabled ) { - L2CACHE_LOGGER.debug( "Query results were not found in cache" ); + if ( loggerTraceEnabled ) { + L2CACHE_LOGGER.trace( "Query results were not found in cache" ); } return null; } if ( !timestampsCache.isUpToDate( spaces, cacheItem.timestamp, session ) ) { - if ( loggerDebugEnabled ) { - L2CACHE_LOGGER.debug( "Cached query results were not up-to-date" ); + if ( loggerTraceEnabled ) { + L2CACHE_LOGGER.trace( "Cached query results were not up-to-date" ); } return null; } - if ( loggerDebugEnabled ) { - L2CACHE_LOGGER.debug( "Returning cached query results" ); + if ( loggerTraceEnabled ) { + L2CACHE_LOGGER.trace( "Returning cached query results" ); } return deepCopy( cacheItem.results ); diff --git a/hibernate-core/src/main/java/org/hibernate/cache/internal/RegionFactoryInitiator.java b/hibernate-core/src/main/java/org/hibernate/cache/internal/RegionFactoryInitiator.java index 78f7c392a99f..9660bb4ca803 100644 --- a/hibernate-core/src/main/java/org/hibernate/cache/internal/RegionFactoryInitiator.java +++ b/hibernate-core/src/main/java/org/hibernate/cache/internal/RegionFactoryInitiator.java @@ -113,12 +113,10 @@ protected RegionFactory resolveRegionFactory(Map configurationVal return registeredFactory; } else { - if ( LOG.isDebugEnabled() ) { - LOG.debugf( - "Cannot default RegionFactory based on registered strategies as `%s` RegionFactory strategies were registered", - implementors - ); - } + LOG.debugf( + "Cannot default RegionFactory based on registered strategies as `%s` RegionFactory strategies were registered", + implementors + ); } return NoCachingRegionFactory.INSTANCE; diff --git a/hibernate-core/src/main/java/org/hibernate/cache/internal/TimestampsCacheEnabledImpl.java b/hibernate-core/src/main/java/org/hibernate/cache/internal/TimestampsCacheEnabledImpl.java index dd5d7add9b67..362d93c30f68 100644 --- a/hibernate-core/src/main/java/org/hibernate/cache/internal/TimestampsCacheEnabledImpl.java +++ b/hibernate-core/src/main/java/org/hibernate/cache/internal/TimestampsCacheEnabledImpl.java @@ -26,7 +26,7 @@ public class TimestampsCacheEnabledImpl implements TimestampsCache { private static final Logger log = Logger.getLogger( TimestampsCacheEnabledImpl.class ); - public static final boolean DEBUG_ENABLED = log.isDebugEnabled(); + public static final boolean TRACE_ENABLED = log.isTraceEnabled(); private final TimestampsRegion timestampsRegion; @@ -52,11 +52,11 @@ public void preInvalidate( final Long timestamp = regionFactory.nextTimestamp() + regionFactory.getTimeout(); final SessionEventListenerManager eventListenerManager = session.getEventListenerManager(); - final boolean debugEnabled = log.isDebugEnabled(); + final boolean traceEnabled = log.isTraceEnabled(); for ( String space : spaces ) { - if ( debugEnabled ) { - log.debugf( "Pre-invalidating space [%s], timestamp: %s", space, timestamp ); + if ( traceEnabled ) { + log.tracef( "Pre-invalidating space [%s], timestamp: %s", space, timestamp ); } final EventMonitor eventMonitor = session.getEventMonitor(); final DiagnosticEvent cachePutEvent = eventMonitor.beginCachePutEvent(); @@ -92,11 +92,11 @@ public void invalidate( final boolean stats = statistics.isStatisticsEnabled(); final Long ts = session.getFactory().getCache().getRegionFactory().nextTimestamp(); - final boolean debugEnabled = log.isDebugEnabled(); + final boolean traceEnabled = log.isTraceEnabled(); for ( String space : spaces ) { - if ( debugEnabled ) { - log.debugf( "Invalidating space [%s], timestamp: %s", space, ts ); + if ( traceEnabled ) { + log.tracef( "Invalidating space [%s], timestamp: %s", space, ts ); } final SessionEventListenerManager eventListenerManager = session.getEventListenerManager(); @@ -152,8 +152,8 @@ private boolean isSpaceOutOfDate( return false; } else { - if ( DEBUG_ENABLED ) { - log.debugf( + if ( TRACE_ENABLED ) { + log.tracef( "[%s] last update timestamp: %s", space, lastUpdate + ", result set timestamp: " + timestamp diff --git a/hibernate-core/src/main/java/org/hibernate/cache/spi/support/AbstractCachedDomainDataAccess.java b/hibernate-core/src/main/java/org/hibernate/cache/spi/support/AbstractCachedDomainDataAccess.java index 0f53eda8484f..e19b27278577 100644 --- a/hibernate-core/src/main/java/org/hibernate/cache/spi/support/AbstractCachedDomainDataAccess.java +++ b/hibernate-core/src/main/java/org/hibernate/cache/spi/support/AbstractCachedDomainDataAccess.java @@ -39,7 +39,7 @@ public DomainDataStorageAccess getStorageAccess() { } protected void clearCache() { - log.debugf( "Clearing cache data map [region=`%s`]", region.getName() ); + log.tracef( "Clearing cache data map [region=`%s`]", region.getName() ); getStorageAccess().evictData(); } diff --git a/hibernate-core/src/main/java/org/hibernate/cache/spi/support/AbstractReadWriteAccess.java b/hibernate-core/src/main/java/org/hibernate/cache/spi/support/AbstractReadWriteAccess.java index 035e73ff7b45..b729bb328e5f 100644 --- a/hibernate-core/src/main/java/org/hibernate/cache/spi/support/AbstractReadWriteAccess.java +++ b/hibernate-core/src/main/java/org/hibernate/cache/spi/support/AbstractReadWriteAccess.java @@ -63,31 +63,31 @@ protected Lock writeLock() { */ @Override public Object get(SharedSessionContractImplementor session, Object key) { - final boolean debugEnabled = log.isDebugEnabled(); - if ( debugEnabled ) { - log.debugf( "Getting cached data from region [`%s` (%s)] by key [%s]", getRegion().getName(), getAccessType(), key ); + final boolean traceEnabled = log.isTraceEnabled(); + if ( traceEnabled ) { + log.tracef( "Getting cached data from region [`%s` (%s)] by key [%s]", getRegion().getName(), getAccessType(), key ); } try { readLock.lock(); final Lockable item = (Lockable) getStorageAccess().getFromCache( key, session ); if ( item == null ) { - if ( debugEnabled ) { - log.debugf( "Cache miss : region = `%s`, key = `%s`", getRegion().getName(), key ); + if ( traceEnabled ) { + log.tracef( "Cache miss : region = `%s`, key = `%s`", getRegion().getName(), key ); } return null; } final boolean readable = item.isReadable( session.getCacheTransactionSynchronization().getCachingTimestamp() ); if ( readable ) { - if ( debugEnabled ) { - log.debugf( "Cache hit : region = `%s`, key = `%s`", getRegion().getName(), key ); + if ( traceEnabled ) { + log.tracef( "Cache hit : region = `%s`, key = `%s`", getRegion().getName(), key ); } return item.getValue(); } else { - if ( debugEnabled ) { - log.debugf( "Cache hit, but item is unreadable/invalid : region = `%s`, key = `%s`", getRegion().getName(), key ); + if ( traceEnabled ) { + log.tracef( "Cache hit, but item is unreadable/invalid : region = `%s`, key = `%s`", getRegion().getName(), key ); } return null; } @@ -104,9 +104,9 @@ public boolean putFromLoad( Object value, Object version) { try { - final boolean debugEnabled = log.isDebugEnabled(); - if ( debugEnabled ) { - log.debugf( "Caching data from load [region=`%s` (%s)] : key[%s] -> value[%s]", getRegion().getName(), getAccessType(), key, value ); + final boolean traceEnabled = log.isTraceEnabled(); + if ( traceEnabled ) { + log.tracef( "Caching data from load [region=`%s` (%s)] : key[%s] -> value[%s]", getRegion().getName(), getAccessType(), key, value ); } writeLock.lock(); Lockable item = (Lockable) getStorageAccess().getFromCache( key, session ); @@ -121,8 +121,8 @@ public boolean putFromLoad( return true; } else { - if ( debugEnabled ) { - log.debugf( + if ( traceEnabled ) { + log.tracef( "Cache put-from-load [region=`%s` (%s), key=`%s`, value=`%s`] failed due to being non-writable", getAccessType(), getRegion().getName(), @@ -156,8 +156,8 @@ public SoftLock lockItem(SharedSessionContractImplementor session, Object key, O writeLock.lock(); long timeout = getRegion().getRegionFactory().nextTimestamp() + getRegion().getRegionFactory().getTimeout(); - if ( log.isDebugEnabled() ) { - log.debugf( "Locking cache item [region=`%s` (%s)] : `%s` (timeout=%s, version=%s)", getRegion().getName(), getAccessType(), key, timeout, version ); + if ( log.isTraceEnabled() ) { + log.tracef( "Locking cache item [region=`%s` (%s)] : `%s` (timeout=%s, version=%s)", getRegion().getName(), getAccessType(), key, timeout, version ); } Lockable item = (Lockable) getStorageAccess().getFromCache( key, session ); @@ -175,8 +175,8 @@ public SoftLock lockItem(SharedSessionContractImplementor session, Object key, O @Override public void unlockItem(SharedSessionContractImplementor session, Object key, SoftLock lock) { try { - if ( log.isDebugEnabled() ) { - log.debugf( + if ( log.isTraceEnabled() ) { + log.tracef( "Unlocking cache item [region=`%s` (%s)] : %s", getRegion().getName(), getAccessType(), @@ -205,7 +205,7 @@ protected void decrementLock(SharedSessionContractImplementor session, Object ke protected void handleLockExpiry(SharedSessionContractImplementor session, Object key, Lockable lock) { L2CACHE_LOGGER.softLockedCacheExpired( getRegion().getName(), key ); - log.debugf( "Cached entry expired : %s", key ); + log.tracef( "Cached entry expired: %s", key ); final RegionFactory regionFactory = getRegion().getRegionFactory(); // create new lock that times out immediately @@ -219,7 +219,7 @@ protected void handleLockExpiry(SharedSessionContractImplementor session, Object @Override public void remove(SharedSessionContractImplementor session, Object key) { if ( getStorageAccess().getFromCache( key, session ) instanceof SoftLock ) { - log.debugf( "Skipping #remove call in read-write access to maintain SoftLock : %s", key ); + log.debugf( "Skipping #remove call in read-write access to maintain SoftLock: %s", key ); // don't do anything... we want the SoftLock to remain in place } else { @@ -285,8 +285,8 @@ public final static class Item implements Serializable, Lockable { @Override public boolean isReadable(long txTimestamp) { - if ( log.isDebugEnabled() ) { - log.debugf( + if ( log.isTraceEnabled() ) { + log.tracef( "Checking readability of read-write cache item [timestamp=`%s`, version=`%s`] : txTimestamp=`%s`", (Object) timestamp, version, @@ -299,8 +299,8 @@ public boolean isReadable(long txTimestamp) { @Override public boolean isWriteable(long txTimestamp, Object newVersion, Comparator versionComparator) { - if ( log.isDebugEnabled() ) { - log.debugf( + if ( log.isTraceEnabled() ) { + log.tracef( "Checking writeability of read-write cache item [timestamp=`%s`, version=`%s`] : txTimestamp=`%s`, newVersion=`%s`", timestamp, version, @@ -372,8 +372,8 @@ public boolean isReadable(long txTimestamp) { @Override public boolean isWriteable(long txTimestamp, Object newVersion, Comparator versionComparator) { - if ( log.isDebugEnabled() ) { - log.debugf( + if ( log.isTraceEnabled() ) { + log.tracef( "Checking writeability of read-write cache lock [timeout=`%s`, lockId=`%s`, version=`%s`, sourceUuid=%s, multiplicity=`%s`, unlockTimestamp=`%s`] : txTimestamp=`%s`, newVersion=`%s`", timeout, lockId, diff --git a/hibernate-core/src/main/java/org/hibernate/cache/spi/support/DomainDataRegionTemplate.java b/hibernate-core/src/main/java/org/hibernate/cache/spi/support/DomainDataRegionTemplate.java index 9a2a99bc06a2..8afacfcf56bd 100644 --- a/hibernate-core/src/main/java/org/hibernate/cache/spi/support/DomainDataRegionTemplate.java +++ b/hibernate-core/src/main/java/org/hibernate/cache/spi/support/DomainDataRegionTemplate.java @@ -67,7 +67,7 @@ public EntityDataAccess generateEntityAccess(EntityDataCachingConfig entityAcces final NavigableRole namedEntityRole = entityAccessConfig.getNavigableRole(); final AccessType accessType = entityAccessConfig.getAccessType(); - log.debugf( "Generating entity cache access [%s] : %s", accessType.getExternalName(), namedEntityRole ); + log.tracef( "Generating entity cache access [%s] : %s", accessType.getExternalName(), namedEntityRole ); switch ( accessType ) { case READ_ONLY: { @@ -128,25 +128,14 @@ public NaturalIdDataAccess generateNaturalIdAccess(NaturalIdDataCachingConfig ac final NavigableRole namedEntityRole = accessConfig.getNavigableRole(); final AccessType accessType = accessConfig.getAccessType(); - log.debugf( "Generating entity natural-id access [%s] : %s", accessType.getExternalName(), namedEntityRole ); + log.tracef( "Generating entity natural-id access [%s] : %s", accessType.getExternalName(), namedEntityRole ); - switch ( accessType ) { - case READ_ONLY: { - return generateReadOnlyNaturalIdAccess( accessConfig ); - } - case READ_WRITE: { - return generateReadWriteNaturalIdAccess( accessConfig ); - } - case NONSTRICT_READ_WRITE: { - return generateNonStrictReadWriteNaturalIdAccess( accessConfig ); - } - case TRANSACTIONAL: { - return generateTransactionalNaturalIdDataAccess( accessConfig ); - } - default: { - throw new IllegalArgumentException( "Unrecognized cache AccessType - " + accessType ); - } - } + return switch ( accessType ) { + case READ_ONLY -> generateReadOnlyNaturalIdAccess( accessConfig ); + case READ_WRITE -> generateReadWriteNaturalIdAccess( accessConfig ); + case NONSTRICT_READ_WRITE -> generateNonStrictReadWriteNaturalIdAccess( accessConfig ); + case TRANSACTIONAL -> generateTransactionalNaturalIdDataAccess( accessConfig ); + }; } protected NaturalIdDataAccess generateReadOnlyNaturalIdAccess(NaturalIdDataCachingConfig accessConfig) { @@ -184,25 +173,14 @@ protected NaturalIdDataAccess generateTransactionalNaturalIdDataAccess(NaturalId public CollectionDataAccess generateCollectionAccess(CollectionDataCachingConfig accessConfig) { final NavigableRole namedCollectionRole = accessConfig.getNavigableRole(); - log.debugf( "Generating collection cache access : %s", namedCollectionRole ); + log.tracef( "Generating collection cache access: %s", namedCollectionRole ); - switch ( accessConfig.getAccessType() ) { - case READ_ONLY: { - return generateReadOnlyCollectionAccess( accessConfig ); - } - case READ_WRITE: { - return generateReadWriteCollectionAccess( accessConfig ); - } - case NONSTRICT_READ_WRITE: { - return generateNonStrictReadWriteCollectionAccess( accessConfig ); - } - case TRANSACTIONAL: { - return generateTransactionalCollectionDataAccess( accessConfig ); - } - default: { - throw new IllegalArgumentException( "Unrecognized cache AccessType - " + accessConfig.getAccessType() ); - } - } + return switch ( accessConfig.getAccessType() ) { + case READ_ONLY -> generateReadOnlyCollectionAccess( accessConfig ); + case READ_WRITE -> generateReadWriteCollectionAccess( accessConfig ); + case NONSTRICT_READ_WRITE -> generateNonStrictReadWriteCollectionAccess( accessConfig ); + case TRANSACTIONAL -> generateTransactionalCollectionDataAccess( accessConfig ); + }; } private CollectionDataAccess generateReadOnlyCollectionAccess(CollectionDataCachingConfig accessConfig) { diff --git a/hibernate-core/src/main/java/org/hibernate/cache/spi/support/EntityReadOnlyAccess.java b/hibernate-core/src/main/java/org/hibernate/cache/spi/support/EntityReadOnlyAccess.java index 58200ec30933..fe3f0058fdeb 100644 --- a/hibernate-core/src/main/java/org/hibernate/cache/spi/support/EntityReadOnlyAccess.java +++ b/hibernate-core/src/main/java/org/hibernate/cache/spi/support/EntityReadOnlyAccess.java @@ -11,7 +11,6 @@ import org.hibernate.cache.spi.access.SoftLock; import org.hibernate.engine.spi.SharedSessionContractImplementor; -import org.jboss.logging.Logger; import static org.hibernate.cache.spi.SecondLevelCacheLogger.L2CACHE_LOGGER; @@ -22,7 +21,6 @@ * @author Steve Ebersole */ public class EntityReadOnlyAccess extends AbstractEntityDataAccess { - private static final Logger log = Logger.getLogger( EntityReadOnlyAccess.class ); public EntityReadOnlyAccess( DomainDataRegion region, @@ -64,7 +62,7 @@ public boolean update( Object value, Object currentVersion, Object previousVersion) { - log.debugf( "Illegal attempt to update item cached as read-only [%s]", key ); +// log.debugf( "Illegal attempt to update item cached as read-only [%s]", key ); throw new UnsupportedOperationException( "Can't update readonly object" ); } @@ -76,7 +74,7 @@ public boolean afterUpdate( Object currentVersion, Object previousVersion, SoftLock lock) { - log.debugf( "Illegal attempt to update item cached as read-only [%s]", key ); +// log.debugf( "Illegal attempt to update item cached as read-only [%s]", key ); throw new UnsupportedOperationException( "Can't write to a readonly object" ); } } diff --git a/hibernate-core/src/main/java/org/hibernate/cfg/Configuration.java b/hibernate-core/src/main/java/org/hibernate/cfg/Configuration.java index 9bfc079ae81e..12d04dd1df71 100644 --- a/hibernate-core/src/main/java/org/hibernate/cfg/Configuration.java +++ b/hibernate-core/src/main/java/org/hibernate/cfg/Configuration.java @@ -1025,7 +1025,7 @@ public Configuration setColumnOrderingStrategy(ColumnOrderingStrategy columnOrde * @throws HibernateException usually indicates an invalid configuration or invalid mapping information */ public SessionFactory buildSessionFactory(ServiceRegistry serviceRegistry) throws HibernateException { - log.debug( "Building session factory using provided StandardServiceRegistry" ); + log.trace( "Building session factory using provided StandardServiceRegistry" ); final MetadataBuilder metadataBuilder = metadataSources.getMetadataBuilder( (StandardServiceRegistry) serviceRegistry ); @@ -1128,7 +1128,7 @@ public SessionFactory buildSessionFactory(ServiceRegistry serviceRegistry) throw * @throws HibernateException usually indicates an invalid configuration or invalid mapping information */ public SessionFactory buildSessionFactory() throws HibernateException { - log.debug( "Building session factory using internal StandardServiceRegistryBuilder" ); + log.trace( "Building session factory using internal StandardServiceRegistryBuilder" ); standardServiceRegistryBuilder.applySettings( properties ); StandardServiceRegistry serviceRegistry = standardServiceRegistryBuilder.build(); try { diff --git a/hibernate-core/src/main/java/org/hibernate/dialect/temptable/TemporaryTableHelper.java b/hibernate-core/src/main/java/org/hibernate/dialect/temptable/TemporaryTableHelper.java index fa7f9b0cca39..2d8ab178515d 100644 --- a/hibernate-core/src/main/java/org/hibernate/dialect/temptable/TemporaryTableHelper.java +++ b/hibernate-core/src/main/java/org/hibernate/dialect/temptable/TemporaryTableHelper.java @@ -71,7 +71,7 @@ public void execute(Connection connection) { } catch (SQLException e) { log.debugf( - "unable to create temporary table [%s]; `%s` failed : %s", + "Unable to create temporary table [%s]; `%s` failed : %s", temporaryTable.getQualifiedTableName(), creationCommand, e.getMessage() @@ -126,7 +126,7 @@ public void execute(Connection connection) { } catch (SQLException e) { log.debugf( - "unable to drop temporary table [%s]; `%s` failed : %s", + "Unable to drop temporary table [%s]; `%s` failed : %s", temporaryTable.getQualifiedTableName(), dropCommand, e.getMessage() diff --git a/hibernate-core/src/main/java/org/hibernate/engine/internal/Collections.java b/hibernate-core/src/main/java/org/hibernate/engine/internal/Collections.java index 8d6941da96cf..d14e8cd3be47 100644 --- a/hibernate-core/src/main/java/org/hibernate/engine/internal/Collections.java +++ b/hibernate-core/src/main/java/org/hibernate/engine/internal/Collections.java @@ -50,8 +50,8 @@ private static void processDereferencedCollection(PersistentCollection coll, final CollectionEntry entry = persistenceContext.getCollectionEntry( coll ); final CollectionPersister loadedPersister = entry.getLoadedPersister(); - if ( loadedPersister != null && LOG.isDebugEnabled() ) { - LOG.debug("Collection dereferenced: " + if ( loadedPersister != null && LOG.isTraceEnabled() ) { + LOG.trace("Collection dereferenced: " + collectionInfoString( loadedPersister, coll, entry.getLoadedKey(), session ) ); } @@ -115,8 +115,8 @@ private static void processNeverReferencedCollection(PersistentCollection col session.getPersistenceContextInternal() .getCollectionEntry( coll ); - if ( LOG.isDebugEnabled() ) { - LOG.debug( "Found collection with unloaded owner: " + + if ( LOG.isTraceEnabled() ) { + LOG.trace( "Found collection with unloaded owner: " + collectionInfoString( entry.getLoadedPersister(), coll, entry.getLoadedKey(), session ) ); } @@ -166,8 +166,8 @@ public static void processReachableCollection( if ( isBytecodeEnhanced && !collection.wasInitialized() ) { // the class of the collection owner is enhanced for lazy loading and we found an un-initialized PersistentCollection // - skip it - if ( LOG.isDebugEnabled() ) { - LOG.debug( "Skipping uninitialized bytecode-lazy collection: " + if ( LOG.isTraceEnabled() ) { + LOG.trace( "Skipping uninitialized bytecode-lazy collection: " + collectionInfoString( persister, collection, ce.getCurrentKey(), session ) ); } ce.setReached( true ); @@ -184,9 +184,9 @@ public static void processReachableCollection( ce.setReached( true ); - if ( LOG.isDebugEnabled() ) { + if ( LOG.isTraceEnabled() ) { if ( collection.wasInitialized() ) { - LOG.debugf( + LOG.tracef( "Collection found: %s, was: %s (initialized)", collectionInfoString( persister, @@ -203,7 +203,7 @@ public static void processReachableCollection( ); } else { - LOG.debugf( + LOG.tracef( "Collection found: %s, was: %s (uninitialized)", collectionInfoString( persister, diff --git a/hibernate-core/src/main/java/org/hibernate/engine/internal/NaturalIdResolutionsImpl.java b/hibernate-core/src/main/java/org/hibernate/engine/internal/NaturalIdResolutionsImpl.java index 52d9365a12da..98cd1ae333c4 100644 --- a/hibernate-core/src/main/java/org/hibernate/engine/internal/NaturalIdResolutionsImpl.java +++ b/hibernate-core/src/main/java/org/hibernate/engine/internal/NaturalIdResolutionsImpl.java @@ -66,7 +66,7 @@ public boolean cacheResolution(Object id, Object naturalId, EntityMappingType en @Override public void cacheResolutionFromLoad(Object id, Object naturalId, EntityMappingType entityDescriptor) { - NaturalIdLogging.NATURAL_ID_LOGGER.debugf( + NaturalIdLogging.NATURAL_ID_LOGGER.tracef( "Caching resolution natural-id resolution from load (%s) : `%s` -> `%s`", entityDescriptor.getEntityName(), naturalId, @@ -100,7 +100,7 @@ private boolean cacheResolutionLocally(Object id, Object naturalId, EntityMappin assert entityDescriptor.getNaturalIdMapping() != null; assert isValidValue( naturalId, entityDescriptor ); - NaturalIdLogging.NATURAL_ID_LOGGER.debugf( + NaturalIdLogging.NATURAL_ID_LOGGER.tracef( "Locally caching natural-id resolution (%s) : `%s` -> `%s`", entityDescriptor.getEntityName(), naturalId, @@ -159,7 +159,7 @@ public void manageLocalResolution( @Override public Object removeLocalResolution(Object id, Object naturalId, EntityMappingType entityDescriptor) { - NaturalIdLogging.NATURAL_ID_LOGGER.debugf( + NaturalIdLogging.NATURAL_ID_LOGGER.tracef( "Removing locally cached natural-id resolution (%s) : `%s` -> `%s`", entityDescriptor.getEntityName(), naturalId, diff --git a/hibernate-core/src/main/java/org/hibernate/engine/internal/StatefulPersistenceContext.java b/hibernate-core/src/main/java/org/hibernate/engine/internal/StatefulPersistenceContext.java index ec8cfdffc5bd..668177d53299 100644 --- a/hibernate-core/src/main/java/org/hibernate/engine/internal/StatefulPersistenceContext.java +++ b/hibernate-core/src/main/java/org/hibernate/engine/internal/StatefulPersistenceContext.java @@ -733,7 +733,7 @@ public boolean reassociateIfUninitializedProxy(Object value) throws MappingExcep public void reassociateProxy(Object value, Object id) throws MappingException { final LazyInitializer lazyInitializer = extractLazyInitializer( value ); if ( lazyInitializer != null ) { - LOG.debugf( "Setting proxy identifier: %s", id ); + LOG.tracef( "Setting proxy identifier: %s", id ); lazyInitializer.setIdentifier( id ); reassociateProxy( lazyInitializer, asHibernateProxy( value ) ); } @@ -1524,7 +1524,7 @@ && isFoundInParent( propertyName, childEntity, persister, collectionPersister, p collectionPersister, unmergedInstance ); - LOG.debugf( + LOG.tracef( "Detached object being merged (corresponding with a managed entity) has a collection that [%s] the detached child.", ( found ? "contains" : "does not contain" ) ); diff --git a/hibernate-core/src/main/java/org/hibernate/engine/jdbc/cursor/internal/StandardRefCursorSupport.java b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/cursor/internal/StandardRefCursorSupport.java index d64bba8af341..35e425d04e90 100644 --- a/hibernate-core/src/main/java/org/hibernate/engine/jdbc/cursor/internal/StandardRefCursorSupport.java +++ b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/cursor/internal/StandardRefCursorSupport.java @@ -92,7 +92,7 @@ public static boolean supportsRefCursors(DatabaseMetaData meta) { } catch (Exception throwable) { //If the driver is not compatible with the Java 8 contract, the method might not exit. - log.debug( "Unexpected error trying to gauge level of JDBC REF_CURSOR support : " + throwable.getMessage() ); + log.debug( "Unexpected error trying to gauge level of JDBC REF_CURSOR support: " + throwable.getMessage() ); return false; } } diff --git a/hibernate-core/src/main/java/org/hibernate/engine/jdbc/env/internal/JdbcEnvironmentInitiator.java b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/env/internal/JdbcEnvironmentInitiator.java index c8a4a645df4e..7b7d0eb78e1a 100644 --- a/hibernate-core/src/main/java/org/hibernate/engine/jdbc/env/internal/JdbcEnvironmentInitiator.java +++ b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/env/internal/JdbcEnvironmentInitiator.java @@ -432,10 +432,10 @@ private static void logDatabaseAndDriver(DatabaseMetaData dbmd) throws SQLExcept if ( log.isDebugEnabled() ) { log.debugf( "Database ->\n" - + " name : %s\n" - + " version : %s\n" - + " major : %s\n" - + " minor : %s", + + " name: %s\n" + + " version: %s\n" + + " major: %s\n" + + " minor: %s", dbmd.getDatabaseProductName(), dbmd.getDatabaseProductVersion(), dbmd.getDatabaseMajorVersion(), @@ -443,16 +443,16 @@ private static void logDatabaseAndDriver(DatabaseMetaData dbmd) throws SQLExcept ); log.debugf( "Driver ->\n" - + " name : %s\n" - + " version : %s\n" - + " major : %s\n" - + " minor : %s", + + " name: %s\n" + + " version: %s\n" + + " major: %s\n" + + " minor: %s", dbmd.getDriverName(), dbmd.getDriverVersion(), dbmd.getDriverMajorVersion(), dbmd.getDriverMinorVersion() ); - log.debugf( "JDBC version : %s.%s", dbmd.getJDBCMajorVersion(), dbmd.getJDBCMinorVersion() ); + log.debugf( "JDBC version: %s.%s", dbmd.getJDBCMajorVersion(), dbmd.getJDBCMinorVersion() ); } } diff --git a/hibernate-core/src/main/java/org/hibernate/engine/jdbc/env/spi/IdentifierHelperBuilder.java b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/env/spi/IdentifierHelperBuilder.java index 81afe15e74f4..ba2d9f2b5d99 100644 --- a/hibernate-core/src/main/java/org/hibernate/engine/jdbc/env/spi/IdentifierHelperBuilder.java +++ b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/env/spi/IdentifierHelperBuilder.java @@ -80,12 +80,12 @@ public void applyIdentifierCasing(DatabaseMetaData metaData) throws SQLException ); if ( unquotedAffirmatives == 0 ) { - log.debug( "JDBC driver metadata reported database stores unquoted identifiers in neither upper, lower nor mixed case" ); + log.trace( "JDBC driver metadata reported database stores unquoted identifiers in neither upper, lower nor mixed case" ); } else { // NOTE : still "dodgy" if more than one is true if ( unquotedAffirmatives > 1 ) { - log.debug( "JDBC driver metadata reported database stores unquoted identifiers in more than one case" ); + log.trace( "JDBC driver metadata reported database stores unquoted identifiers in more than one case" ); } if ( metaData.storesUpperCaseIdentifiers() ) { @@ -107,12 +107,12 @@ else if ( metaData.storesLowerCaseIdentifiers() ) { ); if ( quotedAffirmatives == 0 ) { - log.debug( "JDBC driver metadata reported database stores quoted identifiers in neither upper, lower nor mixed case" ); + log.trace( "JDBC driver metadata reported database stores quoted identifiers in neither upper, lower nor mixed case" ); } else { // NOTE : still "dodgy" if more than one is true if ( quotedAffirmatives > 1 ) { - log.debug( "JDBC driver metadata reported database stores quoted identifiers in more than one case" ); + log.trace( "JDBC driver metadata reported database stores quoted identifiers in more than one case" ); } if ( metaData.storesMixedCaseQuotedIdentifiers() ) { diff --git a/hibernate-core/src/main/java/org/hibernate/engine/jdbc/internal/JdbcCoordinatorImpl.java b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/internal/JdbcCoordinatorImpl.java index f85b2caefff1..6241a214ed6b 100644 --- a/hibernate-core/src/main/java/org/hibernate/engine/jdbc/internal/JdbcCoordinatorImpl.java +++ b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/internal/JdbcCoordinatorImpl.java @@ -265,7 +265,9 @@ public int determineRemainingTransactionTimeOutPeriod() { @Override public void afterStatementExecution() { final ConnectionReleaseMode connectionReleaseMode = connectionReleaseMode(); - if ( TRACE_ENABLED ) LOG.tracev( "Starting after statement execution processing [{0}]", connectionReleaseMode ); + if ( TRACE_ENABLED ) { + LOG.tracev( "Starting after statement execution processing [{0}]", connectionReleaseMode ); + } if ( connectionReleaseMode == AFTER_STATEMENT ) { if ( ! releasesEnabled ) { LOG.debug( "Skipping aggressive release due to manual disabling" ); diff --git a/hibernate-core/src/main/java/org/hibernate/engine/jndi/internal/JndiServiceImpl.java b/hibernate-core/src/main/java/org/hibernate/engine/jndi/internal/JndiServiceImpl.java index a28c45120695..51dabfcd4de0 100644 --- a/hibernate-core/src/main/java/org/hibernate/engine/jndi/internal/JndiServiceImpl.java +++ b/hibernate-core/src/main/java/org/hibernate/engine/jndi/internal/JndiServiceImpl.java @@ -199,7 +199,7 @@ private void bind(Name name, Object value, Context context) { LOG.tracev( "Found intermediate context: {0}", intermediateContextName ); } else { - LOG.tracev( "Creating sub-context: {0}", intermediateContextName ); + LOG.tracev( "Creating subcontext: {0}", intermediateContextName ); try { intermediateContext = intermediateContextBase.createSubcontext( intermediateContextName ); } @@ -210,7 +210,7 @@ private void bind(Name name, Object value, Context context) { intermediateContextBase = intermediateContext; name = name.getSuffix( 1 ); } - LOG.tracev( "Binding : {0}", name ); + LOG.tracev( "Binding: {0}", name ); try { intermediateContextBase.rebind( name, value ); } @@ -218,7 +218,7 @@ private void bind(Name name, Object value, Context context) { throw new JndiException( "Error performing intermediate bind [" + name + "]", e ); } } - LOG.debugf( "Bound name: %s", name ); + LOG.tracef( "Bound name: %s", name ); } @Override diff --git a/hibernate-core/src/main/java/org/hibernate/engine/spi/ActionQueue.java b/hibernate-core/src/main/java/org/hibernate/engine/spi/ActionQueue.java index 35bb17befe83..b65b407a8df3 100644 --- a/hibernate-core/src/main/java/org/hibernate/engine/spi/ActionQueue.java +++ b/hibernate-core/src/main/java/org/hibernate/engine/spi/ActionQueue.java @@ -287,7 +287,7 @@ private void addResolvedEntityInsertAction(AbstractEntityInsertAction insert) { if ( insert.isEarlyInsert() ) { LOG.trace( "Executing insertions before resolved early-insert" ); executeInserts(); - LOG.debug( "Executing identity-insert immediately" ); + LOG.trace( "Executing identity-insert immediately" ); execute( insert ); } else { @@ -605,7 +605,7 @@ private static boolean areTablesToBeUpdated(@Nullable ExecutableList actions, for ( Serializable actionSpace : actions.getQuerySpaces() ) { if ( tableSpaces.contains( actionSpace ) ) { - LOG.debugf( "Changes must be flushed to space: %s", actionSpace ); + LOG.tracef( "Changes must be flushed to space: %s", actionSpace ); return true; } } @@ -618,7 +618,7 @@ private static boolean areTablesToBeUpdated(UnresolvedEntityInsertActions action final Serializable[] spaces = action.getPropertySpaces(); for ( Serializable space : spaces ) { if ( tableSpaces.contains( space ) ) { - LOG.debugf( "Changes must be flushed to space: %s", space ); + LOG.tracef( "Changes must be flushed to space: %s", space ); return true; } } diff --git a/hibernate-core/src/main/java/org/hibernate/engine/spi/CollectionEntry.java b/hibernate-core/src/main/java/org/hibernate/engine/spi/CollectionEntry.java index 29892415e67f..887ee7bbcaa6 100644 --- a/hibernate-core/src/main/java/org/hibernate/engine/spi/CollectionEntry.java +++ b/hibernate-core/src/main/java/org/hibernate/engine/spi/CollectionEntry.java @@ -185,8 +185,8 @@ public void preFlush(PersistentCollection collection) throws HibernateExcepti dirty( collection ); - if ( LOG.isDebugEnabled() && collection.isDirty() && loadedPersister != null ) { - LOG.debug( "Collection dirty: " + collectionInfoString( loadedPersister.getRole(), getLoadedKey() ) ); + if ( LOG.isTraceEnabled() && collection.isDirty() && loadedPersister != null ) { + LOG.trace( "Collection dirty: " + collectionInfoString( loadedPersister.getRole(), getLoadedKey() ) ); } setReached( false ); @@ -265,7 +265,7 @@ public void afterAction(PersistentCollection collection) { * @param storedSnapshot the new stored snapshot */ public void resetStoredSnapshot(PersistentCollection collection, Serializable storedSnapshot) { - LOG.debugf("Reset storedSnapshot to %s for %s", storedSnapshot, this); + LOG.tracef("Reset storedSnapshot to %s for %s", storedSnapshot, this); if ( !fromMerge ) { snapshot = storedSnapshot; diff --git a/hibernate-core/src/main/java/org/hibernate/engine/spi/EffectiveEntityGraph.java b/hibernate-core/src/main/java/org/hibernate/engine/spi/EffectiveEntityGraph.java index f1b60a8b09a4..2ece41266eb9 100644 --- a/hibernate-core/src/main/java/org/hibernate/engine/spi/EffectiveEntityGraph.java +++ b/hibernate-core/src/main/java/org/hibernate/engine/spi/EffectiveEntityGraph.java @@ -81,7 +81,7 @@ public void applyGraph(RootGraphImplementor graph, @Nullable GraphSemantic se verifyWriteability(); - log.debugf( "Setting effective graph state [%s] : %s", semantic.name(), graph ); + log.tracef( "Setting effective graph state [%s] : %s", semantic.name(), graph ); this.semantic = semantic; this.graph = graph; @@ -111,8 +111,8 @@ public void applyConfiguredGraph(@Nullable Map properties) { return; } - RootGraphImplementor fetchHint = (RootGraphImplementor) properties.get( GraphSemantic.FETCH.getJpaHintName() ); - RootGraphImplementor loadHint = (RootGraphImplementor) properties.get( GraphSemantic.LOAD.getJpaHintName() ); + var fetchHint = (RootGraphImplementor) properties.get( GraphSemantic.FETCH.getJpaHintName() ); + var loadHint = (RootGraphImplementor) properties.get( GraphSemantic.LOAD.getJpaHintName() ); if ( fetchHint == null ) { fetchHint = (RootGraphImplementor) properties.get( GraphSemantic.FETCH.getJakartaHintName() ); } @@ -120,25 +120,20 @@ public void applyConfiguredGraph(@Nullable Map properties) { loadHint = (RootGraphImplementor) properties.get( GraphSemantic.LOAD.getJakartaHintName() ); } - if ( fetchHint == null && loadHint == null ) { - log.debugf( "Neither LOAD nor FETCH graph were found in properties" ); - return; - } - - if ( fetchHint != null ) { - if ( loadHint != null ) { - // can't have both - throw new IllegalArgumentException( - "Passed properties contained both a LOAD and a FETCH graph which is illegal - " + - "only one should be passed" - ); + if ( fetchHint != null || loadHint != null ) { + if ( fetchHint != null ) { + if ( loadHint != null ) { + // can't have both + throw new IllegalArgumentException( + "Passed properties contained both a LOAD and a FETCH graph which is illegal - " + + "only one should be passed" + ); + } + applyGraph( fetchHint, GraphSemantic.FETCH ); + } + else { + applyGraph( loadHint, GraphSemantic.LOAD ); } - - applyGraph( fetchHint, GraphSemantic.FETCH ); - } - else { - assert loadHint != null : "@AssumeAssertion(nullness)"; - applyGraph( loadHint, GraphSemantic.LOAD ); } } diff --git a/hibernate-core/src/main/java/org/hibernate/event/internal/AbstractFlushingEventListener.java b/hibernate-core/src/main/java/org/hibernate/event/internal/AbstractFlushingEventListener.java index 319e45d7c66a..684b97970ba2 100644 --- a/hibernate-core/src/main/java/org/hibernate/event/internal/AbstractFlushingEventListener.java +++ b/hibernate-core/src/main/java/org/hibernate/event/internal/AbstractFlushingEventListener.java @@ -191,7 +191,7 @@ private void cascadeOnFlush(EventSource session, EntityPersister persister, Obje private void prepareCollectionFlushes(PersistenceContext persistenceContext) throws HibernateException { // Initialize dirty flags for arrays + collections with composite elements // and reset reached, doupdate, etc. - LOG.debug( "Dirty checking collections" ); + LOG.trace( "Dirty checking collections" ); final var collectionEntries = persistenceContext.getCollectionEntries(); if ( collectionEntries != null ) { final var identityMap = (InstanceIdentityMap, CollectionEntry>) collectionEntries; diff --git a/hibernate-core/src/main/java/org/hibernate/event/internal/AbstractSaveEventListener.java b/hibernate-core/src/main/java/org/hibernate/event/internal/AbstractSaveEventListener.java index 4b7bc926d097..c9057a755015 100644 --- a/hibernate-core/src/main/java/org/hibernate/event/internal/AbstractSaveEventListener.java +++ b/hibernate-core/src/main/java/org/hibernate/event/internal/AbstractSaveEventListener.java @@ -160,7 +160,7 @@ private static Object generateId( else { if ( LOG.isDebugEnabled() ) { // TODO: define toString()s for generators - LOG.debugf( + LOG.tracef( "Generated identifier [%s] using generator '%s'", persister.getIdentifierType().toLoggableString( id, source.getFactory() ), generator.getClass().getName() diff --git a/hibernate-core/src/main/java/org/hibernate/event/internal/EntityCopyAllowedLoggedObserver.java b/hibernate-core/src/main/java/org/hibernate/event/internal/EntityCopyAllowedLoggedObserver.java index f7e5391d31cd..4593547e7650 100644 --- a/hibernate-core/src/main/java/org/hibernate/event/internal/EntityCopyAllowedLoggedObserver.java +++ b/hibernate-core/src/main/java/org/hibernate/event/internal/EntityCopyAllowedLoggedObserver.java @@ -114,7 +114,7 @@ public void clear() { public void topLevelMergeComplete(EventSource session) { // Log the summary. if ( countsByEntityName != null ) { - for ( Map.Entry entry : countsByEntityName.entrySet() ) { + for ( var entry : countsByEntityName.entrySet() ) { LOG.debug( String.format( "Summary: number of %s entities with multiple representations merged: %d", @@ -129,10 +129,10 @@ public void topLevelMergeComplete(EventSource session) { } if ( managedToMergeEntitiesXref != null ) { - for ( Map.Entry> entry : managedToMergeEntitiesXref.entrySet() ) { - Object managedEntity = entry.getKey(); - Set mergeEntities = entry.getValue(); - StringBuilder sb = new StringBuilder( "Details: merged ") + for ( var entry : managedToMergeEntitiesXref.entrySet() ) { + final Object managedEntity = entry.getKey(); + final Set mergeEntities = entry.getValue(); + final StringBuilder sb = new StringBuilder( "Details: merged ") .append( mergeEntities.size() ) .append( " representations of the same entity " ) .append( diff --git a/hibernate-core/src/main/java/org/hibernate/event/internal/EntityCopyObserverFactoryInitiator.java b/hibernate-core/src/main/java/org/hibernate/event/internal/EntityCopyObserverFactoryInitiator.java index 3525918455c9..fa735260b16a 100644 --- a/hibernate-core/src/main/java/org/hibernate/event/internal/EntityCopyObserverFactoryInitiator.java +++ b/hibernate-core/src/main/java/org/hibernate/event/internal/EntityCopyObserverFactoryInitiator.java @@ -37,17 +37,20 @@ public EntityCopyObserverFactory initiateService(final Map confi } else if ( value.equals( EntityCopyNotAllowedObserver.SHORT_NAME ) || value.equals( EntityCopyNotAllowedObserver.class.getName() ) ) { - LOG.debugf( "Configured EntityCopyObserver strategy: %s", EntityCopyNotAllowedObserver.SHORT_NAME ); + LOG.tracef( "Configured EntityCopyObserver strategy: %s", + EntityCopyNotAllowedObserver.SHORT_NAME ); return EntityCopyNotAllowedObserver.FACTORY_OF_SELF; } else if ( value.equals( EntityCopyAllowedObserver.SHORT_NAME ) || value.equals( EntityCopyAllowedObserver.class.getName() ) ) { - LOG.debugf( "Configured EntityCopyObserver strategy: %s", EntityCopyAllowedObserver.SHORT_NAME ); + LOG.tracef( "Configured EntityCopyObserver strategy: %s", + EntityCopyAllowedObserver.SHORT_NAME ); return EntityCopyAllowedObserver.FACTORY_OF_SELF; } else if ( value.equals( EntityCopyAllowedLoggedObserver.SHORT_NAME ) || value.equals( EntityCopyAllowedLoggedObserver.class.getName() ) ) { - LOG.debugf( "Configured EntityCopyObserver strategy: %s", EntityCopyAllowedLoggedObserver.SHORT_NAME ); + LOG.tracef( "Configured EntityCopyObserver strategy: %s", + EntityCopyAllowedLoggedObserver.SHORT_NAME ); return EntityCopyAllowedLoggedObserver.FACTORY_OF_SELF; } else { @@ -59,7 +62,8 @@ else if ( value.equals( EntityCopyAllowedLoggedObserver.SHORT_NAME ) registry.requireService( StrategySelector.class ) .resolveStrategy( EntityCopyObserver.class, value ); final Class observerType = exampleInstance.getClass(); - LOG.debugf( "Configured EntityCopyObserver is a custom implementation of type '%s'", observerType.getName() ); + LOG.tracef( "Configured EntityCopyObserver is a custom implementation of type '%s'", + observerType.getName() ); return new EntityCopyObserverFactoryFromClass( observerType ); } } diff --git a/hibernate-core/src/main/java/org/hibernate/event/service/internal/EventListenerGroupImpl.java b/hibernate-core/src/main/java/org/hibernate/event/service/internal/EventListenerGroupImpl.java index 5f1f1e609820..cece709b80d3 100644 --- a/hibernate-core/src/main/java/org/hibernate/event/service/internal/EventListenerGroupImpl.java +++ b/hibernate-core/src/main/java/org/hibernate/event/service/internal/EventListenerGroupImpl.java @@ -295,7 +295,7 @@ private void handleListenerAddition(T listener, Consumer additionHandler) { final T[] listenersWrite = createListenerArrayForWrite( size ); System.arraycopy( listenersRead, 0, listenersWrite, 0, size ); - final boolean debugEnabled = log.isDebugEnabled(); + final boolean traceEnabled = log.isTraceEnabled(); for ( DuplicationStrategy strategy : duplicationStrategies ) { @@ -306,14 +306,14 @@ private void handleListenerAddition(T listener, Consumer additionHandler) { for ( int i = 0; i < size; i++ ) { final T existingListener = listenersRead[i]; - if ( debugEnabled ) { - log.debugf( "Checking incoming listener [`%s`] for match against existing listener [`%s`]", + if ( traceEnabled ) { + log.tracef( "Checking incoming listener [`%s`] for match against existing listener [`%s`]", listener, existingListener ); } if ( strategy.areMatch( listener, existingListener ) ) { - if ( debugEnabled ) { - log.debugf( "Found listener match between `%s` and `%s`", + if ( traceEnabled ) { + log.tracef( "Found listener match between `%s` and `%s`", listener, existingListener ); } @@ -322,14 +322,14 @@ private void handleListenerAddition(T listener, Consumer additionHandler) { case ERROR: throw new EventListenerRegistrationException( "Duplicate event listener found" ); case KEEP_ORIGINAL: - if ( debugEnabled ) { - log.debugf( "Skipping listener registration (%s) : `%s`", + if ( traceEnabled ) { + log.tracef( "Skipping listener registration (%s) : `%s`", action, listener ); } return; case REPLACE_ORIGINAL: - if ( debugEnabled ) { - log.debugf( "Replacing listener registration (%s) : `%s` -> `%s`", + if ( traceEnabled ) { + log.tracef( "Replacing listener registration (%s) : `%s` -> `%s`", action, existingListener, listener ); } prepareListener( listener ); diff --git a/hibernate-core/src/main/java/org/hibernate/generator/values/internal/GeneratedValuesHelper.java b/hibernate-core/src/main/java/org/hibernate/generator/values/internal/GeneratedValuesHelper.java index 9af7534fee58..1e7ac3aa8fc2 100644 --- a/hibernate-core/src/main/java/org/hibernate/generator/values/internal/GeneratedValuesHelper.java +++ b/hibernate-core/src/main/java/org/hibernate/generator/values/internal/GeneratedValuesHelper.java @@ -103,7 +103,7 @@ public static GeneratedValues getGeneratedValues( if ( LOG.isDebugEnabled() ) { LOG.debug( "Extracted generated values for entity " - + infoString( persister ) + ": " + ArrayHelper.toString(results) ); + + infoString( persister ) + ": " + ArrayHelper.toString( results ) ); } for ( int i = 0; i < results.length; i++ ) { diff --git a/hibernate-core/src/main/java/org/hibernate/graph/internal/parse/GraphParser.java b/hibernate-core/src/main/java/org/hibernate/graph/internal/parse/GraphParser.java index 74c8d71c1bd4..8af0e761dee7 100644 --- a/hibernate-core/src/main/java/org/hibernate/graph/internal/parse/GraphParser.java +++ b/hibernate-core/src/main/java/org/hibernate/graph/internal/parse/GraphParser.java @@ -55,8 +55,8 @@ public AttributeNodeImplementor visitAttributeNode(GraphLanguageParser.At final SubGraphGenerator subGraphCreator; if ( attributeNodeContext.attributePath().attributeQualifier() == null ) { - if ( PARSING_LOGGER.isDebugEnabled() ) { - PARSING_LOGGER.debugf( + if ( PARSING_LOGGER.isTraceEnabled() ) { + PARSING_LOGGER.tracef( "%s Start attribute : %s", StringHelper.repeat( ">>", attributeNodeStack.depth() + 1 ), attributeName @@ -68,8 +68,8 @@ public AttributeNodeImplementor visitAttributeNode(GraphLanguageParser.At else { final String qualifierName = attributeNodeContext.attributePath().attributeQualifier().ATTR_NAME().getText(); - if ( PARSING_LOGGER.isDebugEnabled() ) { - PARSING_LOGGER.debugf( + if ( PARSING_LOGGER.isTraceEnabled() ) { + PARSING_LOGGER.tracef( "%s Start qualified attribute : %s.%s", StringHelper.repeat( ">>", attributeNodeStack.depth() + 1 ), attributeName, @@ -97,8 +97,8 @@ public AttributeNodeImplementor visitAttributeNode(GraphLanguageParser.At } } - if ( PARSING_LOGGER.isDebugEnabled() ) { - PARSING_LOGGER.debugf( + if ( PARSING_LOGGER.isTraceEnabled() ) { + PARSING_LOGGER.tracef( "%s Finished attribute : %s", StringHelper.repeat( "<<", attributeNodeStack.depth() + 1 ), attributeName @@ -134,8 +134,8 @@ private PathQualifierType resolvePathQualifier(String qualifier) { public SubGraphImplementor visitSubGraph(GraphLanguageParser.SubGraphContext subGraphContext) { final String subTypeName = subGraphContext.typeIndicator() == null ? null : subGraphContext.typeIndicator().TYPE_NAME().getText(); - if ( PARSING_LOGGER.isDebugEnabled() ) { - PARSING_LOGGER.debugf( + if ( PARSING_LOGGER.isTraceEnabled() ) { + PARSING_LOGGER.tracef( "%s Starting graph : %s", StringHelper.repeat( ">>", attributeNodeStack.depth() + 2 ), subTypeName @@ -160,8 +160,8 @@ public SubGraphImplementor visitSubGraph(GraphLanguageParser.SubGraphContext graphStack.pop(); } - if ( PARSING_LOGGER.isDebugEnabled() ) { - PARSING_LOGGER.debugf( + if ( PARSING_LOGGER.isTraceEnabled() ) { + PARSING_LOGGER.tracef( "%s Finished graph : %s", StringHelper.repeat( "<<", attributeNodeStack.depth() + 2 ), subGraph.getGraphedType().getTypeName() diff --git a/hibernate-core/src/main/java/org/hibernate/id/IncrementGenerator.java b/hibernate-core/src/main/java/org/hibernate/id/IncrementGenerator.java index 85a58e8b4818..79913b2b898c 100644 --- a/hibernate-core/src/main/java/org/hibernate/id/IncrementGenerator.java +++ b/hibernate-core/src/main/java/org/hibernate/id/IncrementGenerator.java @@ -131,8 +131,8 @@ public void initialize(SqlStringGenerationContext context) { private void initializePreviousValueHolder(SharedSessionContractImplementor session) { previousValueHolder = getIntegralDataTypeHolder( returnClass ); - if ( LOG.isDebugEnabled() ) { - LOG.debugf( "Fetching initial value: %s", sql ); + if ( LOG.isTraceEnabled() ) { + LOG.tracef( "Fetching initial value: %s", sql ); } try { final PreparedStatement st = session.getJdbcCoordinator().getStatementPreparer().prepareStatement( sql ); @@ -146,8 +146,8 @@ private void initializePreviousValueHolder(SharedSessionContractImplementor sess previousValueHolder.initialize( 1L ); } sql = null; - if ( LOG.isDebugEnabled() ) { - LOG.debugf( "First free id: %s", previousValueHolder.makeValue() ); + if ( LOG.isTraceEnabled() ) { + LOG.tracef( "First free id: %s", previousValueHolder.makeValue() ); } } finally { diff --git a/hibernate-core/src/main/java/org/hibernate/id/enhanced/SequenceStructure.java b/hibernate-core/src/main/java/org/hibernate/id/enhanced/SequenceStructure.java index 5586b65f3995..a16536644ee8 100644 --- a/hibernate-core/src/main/java/org/hibernate/id/enhanced/SequenceStructure.java +++ b/hibernate-core/src/main/java/org/hibernate/id/enhanced/SequenceStructure.java @@ -123,8 +123,8 @@ public IntegralDataTypeHolder getNextValue() { rs.next(); final IntegralDataTypeHolder value = getIntegralDataTypeHolder( numberType ); value.initialize( rs, 1 ); - if ( LOG.isDebugEnabled() ) { - LOG.debugf( "Sequence value obtained: %s", value.makeValue() ); + if ( LOG.isTraceEnabled() ) { + LOG.tracef( "Sequence value obtained: %s", value.makeValue() ); } return value; } diff --git a/hibernate-core/src/main/java/org/hibernate/integrator/internal/IntegratorServiceImpl.java b/hibernate-core/src/main/java/org/hibernate/integrator/internal/IntegratorServiceImpl.java index 4bcb6995f706..37c13453a185 100644 --- a/hibernate-core/src/main/java/org/hibernate/integrator/internal/IntegratorServiceImpl.java +++ b/hibernate-core/src/main/java/org/hibernate/integrator/internal/IntegratorServiceImpl.java @@ -46,7 +46,7 @@ public static IntegratorServiceImpl create(LinkedHashSet providedInt private void addIntegrator(Integrator integrator) { if ( LOG.isDebugEnabled() ) { - LOG.debugf( "Adding Integrator [%s].", integrator.getClass().getName() ); + LOG.debugf( "Adding Integrator [%s]", integrator.getClass().getName() ); } integrators.add( integrator ); } diff --git a/hibernate-core/src/main/java/org/hibernate/internal/NaturalIdHelper.java b/hibernate-core/src/main/java/org/hibernate/internal/NaturalIdHelper.java index df68edbdfd2c..fe7043c864a1 100644 --- a/hibernate-core/src/main/java/org/hibernate/internal/NaturalIdHelper.java +++ b/hibernate-core/src/main/java/org/hibernate/internal/NaturalIdHelper.java @@ -76,7 +76,7 @@ public static void performAnyNeededCrossReferenceSynchronizations( if ( entry == null ) { if ( loggerDebugEnabled ) { LoaderLogging.LOADER_LOGGER.debugf( - "Cached natural-id/pk resolution linked to null EntityEntry in persistence context : %s#%s", + "Cached natural-id/pk resolution linked to null EntityEntry in persistence context: %s#%s", entityMappingType.getEntityName(), pk ); diff --git a/hibernate-core/src/main/java/org/hibernate/internal/SessionFactoryImpl.java b/hibernate-core/src/main/java/org/hibernate/internal/SessionFactoryImpl.java index 86e6ec48ff31..a3ef4a7a0b96 100644 --- a/hibernate-core/src/main/java/org/hibernate/internal/SessionFactoryImpl.java +++ b/hibernate-core/src/main/java/org/hibernate/internal/SessionFactoryImpl.java @@ -227,7 +227,7 @@ public SessionFactoryImpl( final MetadataImplementor bootMetamodel, final SessionFactoryOptions options, final BootstrapContext bootstrapContext) { - LOG.debug( "Building session factory" ); + LOG.trace( "Building session factory" ); typeConfiguration = bootstrapContext.getTypeConfiguration(); sessionFactoryOptions = options; @@ -361,7 +361,7 @@ public SessionFactoryImpl( throw e; } - LOG.debug( "Instantiated factory" ); + LOG.trace( "Instantiated factory" ); } private EventMonitor loadEventMonitor() { @@ -773,7 +773,7 @@ public Interceptor getInterceptor() { @Override public Reference getReference() { // from javax.naming.Referenceable - LOG.debug( "Returning a Reference to the factory" ); + LOG.trace( "Returning a Reference to the factory" ); return new Reference( SessionFactoryImpl.class.getName(), new StringRefAddr( "uuid", getUuid() ), @@ -1580,7 +1580,9 @@ private static SessionFactory locateSessionFactoryOnDeserialization(String uuid, throws InvalidObjectException{ final SessionFactory uuidResult = SessionFactoryRegistry.INSTANCE.getSessionFactory( uuid ); if ( uuidResult != null ) { - LOG.debug( "Resolved factory by UUID: " + uuid ); + if ( LOG.isTraceEnabled() ) { + LOG.trace( "Resolved factory by UUID: " + uuid ); + } return uuidResult; } @@ -1589,7 +1591,9 @@ private static SessionFactory locateSessionFactoryOnDeserialization(String uuid, if ( name != null ) { final SessionFactory namedResult = SessionFactoryRegistry.INSTANCE.getNamedSessionFactory( name ); if ( namedResult != null ) { - LOG.debug( "Resolved factory by name: " + name ); + if ( LOG.isTraceEnabled() ) { + LOG.trace( "Resolved factory by name: " + name ); + } return namedResult; } } diff --git a/hibernate-core/src/main/java/org/hibernate/internal/SessionFactoryRegistry.java b/hibernate-core/src/main/java/org/hibernate/internal/SessionFactoryRegistry.java index 09b86638edac..8b5ece7f29f9 100644 --- a/hibernate-core/src/main/java/org/hibernate/internal/SessionFactoryRegistry.java +++ b/hibernate-core/src/main/java/org/hibernate/internal/SessionFactoryRegistry.java @@ -48,7 +48,7 @@ public class SessionFactoryRegistry { private final ConcurrentHashMap nameUuidXref = new ConcurrentHashMap<>(); private SessionFactoryRegistry() { - LOG.debugf( "Initializing SessionFactoryRegistry : %s", this ); + LOG.tracef( "Initializing SessionFactoryRegistry: %s", this ); } /** @@ -146,14 +146,14 @@ public void removeSessionFactory( * @return The SessionFactory */ public SessionFactoryImplementor getNamedSessionFactory(String name) { - LOG.debugf( "Lookup: name=%s", name ); + LOG.tracef( "Lookup: name=%s", name ); final String uuid = nameUuidXref.get( name ); // protect against NPE -- see HHH-8428 return uuid == null ? null : getSessionFactory( uuid ); } public SessionFactoryImplementor getSessionFactory(String uuid) { - LOG.debugf( "Lookup: uid=%s", uuid ); + LOG.tracef( "Lookup: uid=%s", uuid ); final SessionFactoryImplementor sessionFactory = sessionFactoryMap.get( uuid ); if ( sessionFactory == null && LOG.isDebugEnabled() ) { LOG.debugf( "Not found: %s", uuid ); @@ -234,7 +234,7 @@ public void namingExceptionThrown(NamingExceptionEvent evt) { public static class ObjectFactoryImpl implements ObjectFactory { @Override public Object getObjectInstance(Object reference, Name name, Context nameCtx, Hashtable environment) { - LOG.debugf( "JNDI lookup: %s", name ); + LOG.tracef( "JNDI lookup: %s", name ); final String uuid = (String) ( (Reference) reference ).get( 0 ).getContent(); LOG.tracef( "Resolved to UUID = %s", uuid ); return INSTANCE.getSessionFactory( uuid ); diff --git a/hibernate-core/src/main/java/org/hibernate/internal/SessionFactoryRegistryMessageLogger.java b/hibernate-core/src/main/java/org/hibernate/internal/SessionFactoryRegistryMessageLogger.java index b29fc18b408f..5a4b65f9aaf0 100644 --- a/hibernate-core/src/main/java/org/hibernate/internal/SessionFactoryRegistryMessageLogger.java +++ b/hibernate-core/src/main/java/org/hibernate/internal/SessionFactoryRegistryMessageLogger.java @@ -21,6 +21,7 @@ import static org.jboss.logging.Logger.Level.DEBUG; import static org.jboss.logging.Logger.Level.ERROR; import static org.jboss.logging.Logger.Level.INFO; +import static org.jboss.logging.Logger.Level.TRACE; import static org.jboss.logging.Logger.Level.WARN; import static org.jboss.logging.Logger.getMessageLogger; @@ -89,7 +90,7 @@ public interface SessionFactoryRegistryMessageLogger extends BasicLogger { @Message(value = "A SessionFactory was successfully bound to name: %s", id = 20282) void factoryBoundToJndi(String name); - @LogMessage(level = DEBUG) + @LogMessage(level = TRACE) @Message(value = "Not binding SessionFactory to JNDI, no JNDI name configured", id = 20385) void notBindingSessionFactory(); } diff --git a/hibernate-core/src/main/java/org/hibernate/internal/SessionImpl.java b/hibernate-core/src/main/java/org/hibernate/internal/SessionImpl.java index f5bec2513a04..17982bb0f9f8 100644 --- a/hibernate-core/src/main/java/org/hibernate/internal/SessionImpl.java +++ b/hibernate-core/src/main/java/org/hibernate/internal/SessionImpl.java @@ -473,7 +473,7 @@ public boolean isOpen() { protected void checkSessionFactoryOpen() { if ( !getFactory().isOpen() ) { - log.debug( "Forcing-closing session since factory is already closed" ); + log.trace( "Forcing-closing session since factory is already closed" ); setClosed(); } } @@ -1015,7 +1015,7 @@ public Object get(String entityName, Object id) { public Object immediateLoad(String entityName, Object id) { if ( log.isDebugEnabled() ) { final EntityPersister persister = requireEntityPersister( entityName ); - log.debugf( "Initializing proxy: %s", infoString( persister, id, getFactory() ) ); + log.tracef( "Initializing proxy: %s", infoString( persister, id, getFactory() ) ); } final LoadEvent event = makeLoadEvent( entityName, id, getReadOnlyFromLoadQueryInfluencers(), true ); fireLoadNoChecks( event, IMMEDIATE_LOAD ); @@ -1037,7 +1037,7 @@ public Object internalLoad(String entityName, Object id, boolean eager, boolean clearedEffectiveGraph = false; } else { - log.debug("Clearing effective entity graph for subsequent select"); + log.trace( "Clearing effective entity graph for subsequent select" ); clearedEffectiveGraph = true; effectiveEntityGraph.clear(); } @@ -1476,8 +1476,8 @@ public void forceFlush(EntityEntry entityEntry) { @Override public void forceFlush(EntityKey key) { - if ( log.isDebugEnabled() ) { - log.debugf("Flushing to force deletion of re-saved object: " + if ( log.isTraceEnabled() ) { + log.tracef("Flushing to force deletion of re-saved object: " + infoString( key.getPersister(), key.getIdentifier(), getFactory() ) ); } diff --git a/hibernate-core/src/main/java/org/hibernate/internal/StatelessSessionImpl.java b/hibernate-core/src/main/java/org/hibernate/internal/StatelessSessionImpl.java index 408451eec3ce..5cc42be041b7 100644 --- a/hibernate-core/src/main/java/org/hibernate/internal/StatelessSessionImpl.java +++ b/hibernate-core/src/main/java/org/hibernate/internal/StatelessSessionImpl.java @@ -1034,9 +1034,7 @@ public Object internalLoad( final Object proxy = holder == null ? null : holder.getProxy(); if ( proxy != null ) { - if ( LOG.isTraceEnabled() ) { - LOG.trace( "Entity proxy found in session cache" ); - } + LOG.trace( "Entity proxy found in session cache" ); if ( LOG.isDebugEnabled() && extractLazyInitializer( proxy ).isUnwrap() ) { LOG.debug( "Ignoring NO_PROXY to honor laziness" ); } @@ -1046,9 +1044,8 @@ public Object internalLoad( // specialized handling for entities with subclasses with a HibernateProxy factory if ( entityMetamodel.hasSubclasses() ) { - // entities with subclasses that define a ProxyFactory can create - // a HibernateProxy. - LOG.debug( "Creating a HibernateProxy for to-one association with subclasses to honor laziness" ); + // entities with subclasses that define a ProxyFactory can create a HibernateProxy. + LOG.trace( "Creating a HibernateProxy for to-one association with subclasses to honor laziness" ); return createProxy( entityKey ); } return enhancementMetadata.createEnhancedProxy( entityKey, false, this ); diff --git a/hibernate-core/src/main/java/org/hibernate/internal/log/ConnectionAccessLogger.java b/hibernate-core/src/main/java/org/hibernate/internal/log/ConnectionAccessLogger.java index 128356353347..9e46ae7cda76 100644 --- a/hibernate-core/src/main/java/org/hibernate/internal/log/ConnectionAccessLogger.java +++ b/hibernate-core/src/main/java/org/hibernate/internal/log/ConnectionAccessLogger.java @@ -5,7 +5,6 @@ package org.hibernate.internal.log; import org.hibernate.Internal; -import org.hibernate.engine.jdbc.connections.spi.JdbcConnectionAccess; import org.jboss.logging.BasicLogger; import org.jboss.logging.Logger; @@ -16,7 +15,7 @@ import java.lang.invoke.MethodHandles; -import static org.jboss.logging.Logger.Level.INFO; +import static org.jboss.logging.Logger.Level.TRACE; /** * @author Steve Ebersole @@ -41,11 +40,11 @@ public interface ConnectionAccessLogger extends BasicLogger { ); - @LogMessage(level = INFO) + @LogMessage(level = TRACE) @Message( - value = "Connection obtained from JdbcConnectionAccess [%s] for (non-JTA) DDL execution was not in auto-commit mode; " + + value = "Connection obtained from JdbcConnectionAccess for (non-JTA) DDL execution was not in auto-commit mode; " + "the Connection 'local transaction' will be committed and the Connection will be set into auto-commit mode.", id = 10001501 ) - void informConnectionLocalTransactionForNonJtaDdl(JdbcConnectionAccess jdbcConnectionAccess); + void informConnectionLocalTransactionForNonJtaDdl(); } diff --git a/hibernate-core/src/main/java/org/hibernate/jpa/HibernatePersistenceProvider.java b/hibernate-core/src/main/java/org/hibernate/jpa/HibernatePersistenceProvider.java index 48cb9fd960b1..d72bf0cdab71 100644 --- a/hibernate-core/src/main/java/org/hibernate/jpa/HibernatePersistenceProvider.java +++ b/hibernate-core/src/main/java/org/hibernate/jpa/HibernatePersistenceProvider.java @@ -77,7 +77,7 @@ private EntityManagerFactoryBuilder getEntityManagerFactoryBuilderOrNull(String final Map integration = wrap( properties ); final Collection units = locatePersistenceUnits( integration, providedClassLoader, providedClassLoaderService ); - log.debugf( "Located and parsed %s persistence units; checking each", units.size() ); + log.tracef( "Located and parsed %s persistence units; checking each", units.size() ); if ( persistenceUnitName == null && units.size() > 1 ) { // no persistence-unit name to look for was given and we found multiple persistence-units @@ -85,8 +85,8 @@ private EntityManagerFactoryBuilder getEntityManagerFactoryBuilderOrNull(String } for ( PersistenceUnitDescriptor persistenceUnit : units ) { - if ( log.isDebugEnabled() ) { - log.debugf( + if ( log.isTraceEnabled() ) { + log.tracef( "Checking persistence-unit [name=%s, explicit-provider=%s] against incoming persistence unit name [%s]", persistenceUnit.getName(), persistenceUnit.getProviderClassName(), @@ -96,13 +96,13 @@ private EntityManagerFactoryBuilder getEntityManagerFactoryBuilderOrNull(String final boolean matches = persistenceUnitName == null || persistenceUnit.getName().equals( persistenceUnitName ); if ( !matches ) { - log.debug( "Excluding from consideration due to name mis-match" ); + log.tracef( "Excluding from consideration due to name mismatch" ); continue; } // See if we (Hibernate) are the persistence provider if ( ! ProviderChecker.isProvider( persistenceUnit, properties ) ) { - log.debug( "Excluding from consideration due to provider mis-match" ); + log.tracef( "Excluding from consideration due to provider mismatch" ); continue; } diff --git a/hibernate-core/src/main/java/org/hibernate/jpa/boot/internal/PersistenceUnitInfoDescriptor.java b/hibernate-core/src/main/java/org/hibernate/jpa/boot/internal/PersistenceUnitInfoDescriptor.java index 32c3199ee83e..801a21cc225a 100644 --- a/hibernate-core/src/main/java/org/hibernate/jpa/boot/internal/PersistenceUnitInfoDescriptor.java +++ b/hibernate-core/src/main/java/org/hibernate/jpa/boot/internal/PersistenceUnitInfoDescriptor.java @@ -132,8 +132,9 @@ public void pushClassTransformer(EnhancementContext enhancementContext) { // During testing, we will return a null temp class loader // in cases where we don't care about enhancement if ( persistenceUnitInfo.getNewTempClassLoader() != null ) { - if ( LOGGER.isDebugEnabled() ) { - LOGGER.debug( "Pushing class transformers for PU named '" + getName() + "' on loading classloader " + enhancementContext.getLoadingClassLoader() ); + if ( LOGGER.isTraceEnabled() ) { + LOGGER.trace( "Pushing class transformers for PU named '" + getName() + + "' on loading classloader " + enhancementContext.getLoadingClassLoader() ); } final EnhancingClassTransformerImpl classTransformer = new EnhancingClassTransformerImpl( enhancementContext ); diff --git a/hibernate-core/src/main/java/org/hibernate/jpa/boot/spi/ProviderChecker.java b/hibernate-core/src/main/java/org/hibernate/jpa/boot/spi/ProviderChecker.java index 634485ffccf9..da14f4706611 100644 --- a/hibernate-core/src/main/java/org/hibernate/jpa/boot/spi/ProviderChecker.java +++ b/hibernate-core/src/main/java/org/hibernate/jpa/boot/spi/ProviderChecker.java @@ -85,7 +85,7 @@ public static String extractRequestedProviderName(PersistenceUnitDescriptor pers return persistenceUnitRequestedProvider; } - // NOTE : if no provider requested we assume we are the provider (the calls got to us somehow...) + // NOTE: if no provider requested, we assume we are the provider (the calls got to us somehow...) log.debug( "No PersistenceProvider explicitly requested, assuming Hibernate" ); return HibernatePersistenceProvider.class.getName(); } diff --git a/hibernate-core/src/main/java/org/hibernate/jpa/internal/util/FlushModeTypeHelper.java b/hibernate-core/src/main/java/org/hibernate/jpa/internal/util/FlushModeTypeHelper.java index 47b7c8cac1c0..ee8527359364 100644 --- a/hibernate-core/src/main/java/org/hibernate/jpa/internal/util/FlushModeTypeHelper.java +++ b/hibernate-core/src/main/java/org/hibernate/jpa/internal/util/FlushModeTypeHelper.java @@ -101,11 +101,11 @@ public static FlushMode interpretExternalSetting(String externalName) { } try { - log.debugf( "Attempting to interpret external setting [%s] as FlushMode name", externalName ); + log.tracef( "Attempting to interpret external setting [%s] as FlushMode name", externalName ); return FlushMode.valueOf( externalName.toUpperCase( Locale.ROOT) ); } catch ( IllegalArgumentException e ) { - log.debugf( "Attempting to interpret external setting [%s] as FlushModeType name", externalName ); + log.tracef( "Attempting to interpret external setting [%s] as FlushModeType name", externalName ); } try { diff --git a/hibernate-core/src/main/java/org/hibernate/jpa/internal/util/LogHelper.java b/hibernate-core/src/main/java/org/hibernate/jpa/internal/util/LogHelper.java index 0c678371cbd0..5ae85996e0e4 100644 --- a/hibernate-core/src/main/java/org/hibernate/jpa/internal/util/LogHelper.java +++ b/hibernate-core/src/main/java/org/hibernate/jpa/internal/util/LogHelper.java @@ -90,7 +90,7 @@ public static void logPersistenceUnitInformation(PersistenceUnitDescriptor descr sb.append( "Properties [" ); Properties properties = descriptor.getProperties(); if (properties != null) { - Enumeration names = properties.propertyNames(); + Enumeration names = properties.propertyNames(); while ( names.hasMoreElements() ) { String name = (String) names.nextElement(); sb.append( "\n\t\t" ).append( name ).append( ": " ).append( properties.getProperty( name ) ); diff --git a/hibernate-core/src/main/java/org/hibernate/loader/ast/internal/AbstractCollectionBatchLoader.java b/hibernate-core/src/main/java/org/hibernate/loader/ast/internal/AbstractCollectionBatchLoader.java index f81685491747..3e892ea7e800 100644 --- a/hibernate-core/src/main/java/org/hibernate/loader/ast/internal/AbstractCollectionBatchLoader.java +++ b/hibernate-core/src/main/java/org/hibernate/loader/ast/internal/AbstractCollectionBatchLoader.java @@ -79,8 +79,8 @@ public int getKeyJdbcCount() { @Override public PersistentCollection load(Object key, SharedSessionContractImplementor session) { - if ( MULTI_KEY_LOAD_LOGGER.isDebugEnabled() ) { - MULTI_KEY_LOAD_LOGGER.debugf( "Batch fetching collection: %s.%s", + if ( MULTI_KEY_LOAD_LOGGER.isTraceEnabled() ) { + MULTI_KEY_LOAD_LOGGER.tracef( "Batch fetching collection: %s.%s", getLoadable().getNavigableRole().getFullPath(), key ); } @@ -105,8 +105,8 @@ protected void finishInitializingKey(Object key, SharedSessionContractImplemento return; } - if ( MULTI_KEY_LOAD_LOGGER.isDebugEnabled() ) { - MULTI_KEY_LOAD_LOGGER.debugf( "Finishing initializing batch-fetched collection: %s.%s", + if ( MULTI_KEY_LOAD_LOGGER.isTraceEnabled() ) { + MULTI_KEY_LOAD_LOGGER.tracef( "Finishing initializing batch-fetched collection: %s.%s", attributeMapping.getNavigableRole().getFullPath(), key ); } diff --git a/hibernate-core/src/main/java/org/hibernate/loader/ast/internal/AbstractEntityBatchLoader.java b/hibernate-core/src/main/java/org/hibernate/loader/ast/internal/AbstractEntityBatchLoader.java index 29227c9d0c9c..4a2eea7e0757 100644 --- a/hibernate-core/src/main/java/org/hibernate/loader/ast/internal/AbstractEntityBatchLoader.java +++ b/hibernate-core/src/main/java/org/hibernate/loader/ast/internal/AbstractEntityBatchLoader.java @@ -44,8 +44,8 @@ public final T load( LockOptions lockOptions, Boolean readOnly, SharedSessionContractImplementor session) { - if ( MULTI_KEY_LOAD_LOGGER.isDebugEnabled() ) { - MULTI_KEY_LOAD_LOGGER.debugf( "Batch fetching entity `%s#%s`", getLoadable().getEntityName(), id ); + if ( MULTI_KEY_LOAD_LOGGER.isTraceEnabled() ) { + MULTI_KEY_LOAD_LOGGER.tracef( "Batch fetching entity `%s#%s`", getLoadable().getEntityName(), id ); } final Object[] ids = resolveIdsToInitialize( id, session ); @@ -58,8 +58,8 @@ public T load( Object entityInstance, LockOptions lockOptions, SharedSessionContractImplementor session) { - if ( MULTI_KEY_LOAD_LOGGER.isDebugEnabled() ) { - MULTI_KEY_LOAD_LOGGER.debugf( "Batch fetching entity `%s#%s`", getLoadable().getEntityName(), id ); + if ( MULTI_KEY_LOAD_LOGGER.isTraceEnabled() ) { + MULTI_KEY_LOAD_LOGGER.tracef( "Batch fetching entity `%s#%s`", getLoadable().getEntityName(), id ); } final Object[] ids = resolveIdsToInitialize( id, session ); diff --git a/hibernate-core/src/main/java/org/hibernate/loader/ast/internal/CollectionBatchLoaderArrayParam.java b/hibernate-core/src/main/java/org/hibernate/loader/ast/internal/CollectionBatchLoaderArrayParam.java index ccbd81605efa..6fecce326b0a 100644 --- a/hibernate-core/src/main/java/org/hibernate/loader/ast/internal/CollectionBatchLoaderArrayParam.java +++ b/hibernate-core/src/main/java/org/hibernate/loader/ast/internal/CollectionBatchLoaderArrayParam.java @@ -58,8 +58,8 @@ public CollectionBatchLoaderArrayParam( SessionFactoryImplementor sessionFactory) { super( domainBatchSize, loadQueryInfluencers, attributeMapping, sessionFactory ); - if ( MULTI_KEY_LOAD_LOGGER.isDebugEnabled() ) { - MULTI_KEY_LOAD_LOGGER.debugf( + if ( MULTI_KEY_LOAD_LOGGER.isTraceEnabled() ) { + MULTI_KEY_LOAD_LOGGER.tracef( "Using ARRAY batch fetching strategy for collection `%s` : %s", attributeMapping.getNavigableRole().getFullPath(), domainBatchSize @@ -115,8 +115,8 @@ private PersistentCollection loadEmbeddable( Object keyBeingLoaded, SharedSessionContractImplementor session, ForeignKeyDescriptor keyDescriptor) { - if ( MULTI_KEY_LOAD_LOGGER.isDebugEnabled() ) { - MULTI_KEY_LOAD_LOGGER.debugf( + if ( MULTI_KEY_LOAD_LOGGER.isTraceEnabled() ) { + MULTI_KEY_LOAD_LOGGER.tracef( "Batch fetching collection: %s.%s", getLoadable().getNavigableRole().getFullPath(), keyBeingLoaded ); @@ -167,8 +167,8 @@ private PersistentCollection loadEmbeddable( @Override void initializeKeys(Object key, Object[] keysToInitialize, SharedSessionContractImplementor session) { - if ( MULTI_KEY_LOAD_LOGGER.isDebugEnabled() ) { - MULTI_KEY_LOAD_LOGGER.debugf( + if ( MULTI_KEY_LOAD_LOGGER.isTraceEnabled() ) { + MULTI_KEY_LOAD_LOGGER.tracef( "Collection keys to batch-fetch initialize (`%s#%s`) %s", getLoadable().getNavigableRole().getFullPath(), key, diff --git a/hibernate-core/src/main/java/org/hibernate/loader/ast/internal/CollectionBatchLoaderInPredicate.java b/hibernate-core/src/main/java/org/hibernate/loader/ast/internal/CollectionBatchLoaderInPredicate.java index 1a4b378d87b0..00084429cfb1 100644 --- a/hibernate-core/src/main/java/org/hibernate/loader/ast/internal/CollectionBatchLoaderInPredicate.java +++ b/hibernate-core/src/main/java/org/hibernate/loader/ast/internal/CollectionBatchLoaderInPredicate.java @@ -51,7 +51,7 @@ public CollectionBatchLoaderInPredicate( .getBatchLoadSizingStrategy() .determineOptimalBatchLoadSize( keyColumnCount, domainBatchSize, false ); if ( MULTI_KEY_LOAD_LOGGER.isDebugEnabled() ) { - MULTI_KEY_LOAD_LOGGER.debugf( + MULTI_KEY_LOAD_LOGGER.tracef( "Using IN-predicate batch fetching strategy for collection `%s` : %s (%s)", attributeMapping.getNavigableRole().getFullPath(), sqlBatchSize, @@ -90,7 +90,7 @@ public CollectionBatchLoaderInPredicate( void initializeKeys(Object key, Object[] keysToInitialize, SharedSessionContractImplementor session) { final boolean loggerDebugEnabled = MULTI_KEY_LOAD_LOGGER.isDebugEnabled(); if ( loggerDebugEnabled ) { - MULTI_KEY_LOAD_LOGGER.debugf( + MULTI_KEY_LOAD_LOGGER.tracef( "Collection keys to batch-fetch initialize (`%s#%s`) %s", getLoadable().getNavigableRole().getFullPath(), key, @@ -126,7 +126,7 @@ void initializeKeys(Object key, Object[] keysToInitialize, SharedSessionContract }, (startIndex) -> { if ( loggerDebugEnabled ) { - MULTI_KEY_LOAD_LOGGER.debugf( + MULTI_KEY_LOAD_LOGGER.tracef( "Processing collection batch-fetch chunk (`%s#%s`) %s - %s", getLoadable().getNavigableRole().getFullPath(), key, @@ -137,7 +137,7 @@ void initializeKeys(Object key, Object[] keysToInitialize, SharedSessionContract }, (startIndex, nonNullElementCount) -> { if ( loggerDebugEnabled ) { - MULTI_KEY_LOAD_LOGGER.debugf( + MULTI_KEY_LOAD_LOGGER.tracef( "Finishing collection batch-fetch chunk (`%s#%s`) %s - %s (%s)", getLoadable().getNavigableRole().getFullPath(), key, diff --git a/hibernate-core/src/main/java/org/hibernate/loader/ast/internal/EntityBatchLoaderArrayParam.java b/hibernate-core/src/main/java/org/hibernate/loader/ast/internal/EntityBatchLoaderArrayParam.java index 098fc4709502..c03a4fdc1cdc 100644 --- a/hibernate-core/src/main/java/org/hibernate/loader/ast/internal/EntityBatchLoaderArrayParam.java +++ b/hibernate-core/src/main/java/org/hibernate/loader/ast/internal/EntityBatchLoaderArrayParam.java @@ -67,8 +67,8 @@ public EntityBatchLoaderArrayParam( super( entityDescriptor, loadQueryInfluencers ); this.domainBatchSize = domainBatchSize; - if ( MULTI_KEY_LOAD_LOGGER.isDebugEnabled() ) { - MULTI_KEY_LOAD_LOGGER.debugf( + if ( MULTI_KEY_LOAD_LOGGER.isTraceEnabled() ) { + MULTI_KEY_LOAD_LOGGER.tracef( "Batch fetching enabled for `%s` (entity) using ARRAY strategy : %s", entityDescriptor.getEntityName(), domainBatchSize @@ -126,8 +126,8 @@ protected void initializeEntities( LockOptions lockOptions, Boolean readOnly, SharedSessionContractImplementor session) { - if ( MULTI_KEY_LOAD_LOGGER.isDebugEnabled() ) { - MULTI_KEY_LOAD_LOGGER.debugf( "Ids to batch-fetch initialize (`%s#%s`) %s", + if ( MULTI_KEY_LOAD_LOGGER.isTraceEnabled() ) { + MULTI_KEY_LOAD_LOGGER.tracef( "Ids to batch-fetch initialize (`%s#%s`) %s", getLoadable().getEntityName(), id, Arrays.toString(idsToInitialize) ); } diff --git a/hibernate-core/src/main/java/org/hibernate/loader/ast/internal/EntityBatchLoaderInPredicate.java b/hibernate-core/src/main/java/org/hibernate/loader/ast/internal/EntityBatchLoaderInPredicate.java index 310a399d2e4e..86c9c772a9ad 100644 --- a/hibernate-core/src/main/java/org/hibernate/loader/ast/internal/EntityBatchLoaderInPredicate.java +++ b/hibernate-core/src/main/java/org/hibernate/loader/ast/internal/EntityBatchLoaderInPredicate.java @@ -61,9 +61,9 @@ public EntityBatchLoaderInPredicate( sessionFactory.getJdbcServices().getDialect().getBatchLoadSizingStrategy() .determineOptimalBatchLoadSize( idColumnCount, domainBatchSize, false ); - if ( MULTI_KEY_LOAD_LOGGER.isDebugEnabled() ) { - MULTI_KEY_LOAD_LOGGER.debugf( - "Batch fetching `%s` entity using padded IN-list : %s (%s)", + if ( MULTI_KEY_LOAD_LOGGER.isTraceEnabled() ) { + MULTI_KEY_LOAD_LOGGER.tracef( + "Batch fetching `%s` entity using padded IN-list: %s (%s)", entityDescriptor.getEntityName(), domainBatchSize, sqlBatchSize @@ -121,8 +121,8 @@ protected void initializeEntities( LockOptions lockOptions, Boolean readOnly, SharedSessionContractImplementor session) { - if ( MULTI_KEY_LOAD_LOGGER.isDebugEnabled() ) { - MULTI_KEY_LOAD_LOGGER.debugf( "Ids to batch-fetch initialize (`%s#%s`) %s", + if ( MULTI_KEY_LOAD_LOGGER.isTraceEnabled() ) { + MULTI_KEY_LOAD_LOGGER.tracef( "Ids to batch-fetch initialize (`%s#%s`) %s", getLoadable().getEntityName(), pkValue, Arrays.toString(idsToInitialize) ); } @@ -156,8 +156,8 @@ protected void initializeEntities( } }, (startIndex) -> { - if ( MULTI_KEY_LOAD_LOGGER.isDebugEnabled() ) { - MULTI_KEY_LOAD_LOGGER.debugf( + if ( MULTI_KEY_LOAD_LOGGER.isTraceEnabled() ) { + MULTI_KEY_LOAD_LOGGER.tracef( "Processing entity batch-fetch chunk (`%s#%s`) %s - %s", getLoadable().getEntityName(), pkValue, diff --git a/hibernate-core/src/main/java/org/hibernate/loader/internal/BaseNaturalIdLoadAccessImpl.java b/hibernate-core/src/main/java/org/hibernate/loader/internal/BaseNaturalIdLoadAccessImpl.java index 7b2e2cf9c3da..223078388a3d 100644 --- a/hibernate-core/src/main/java/org/hibernate/loader/internal/BaseNaturalIdLoadAccessImpl.java +++ b/hibernate-core/src/main/java/org/hibernate/loader/internal/BaseNaturalIdLoadAccessImpl.java @@ -163,7 +163,7 @@ protected final T doGetReference(Object normalizedNaturalIdValue) { return (T) getIdentifierLoadAccess().getReference( cachedResolution ); } else { - LoaderLogging.LOADER_LOGGER.debugf( + LoaderLogging.LOADER_LOGGER.tracef( "Selecting entity identifier by natural-id for `#getReference` handling - %s : %s", entityPersister().getEntityName(), normalizedNaturalIdValue @@ -176,7 +176,6 @@ protected final T doGetReference(Object normalizedNaturalIdValue) { } } - @SuppressWarnings("unchecked") protected final T doLoad(Object normalizedNaturalIdValue) { performAnyNeededCrossReferenceSynchronizations( synchronizationEnabled, entityDescriptor, context.getSession() ); @@ -199,6 +198,7 @@ protected final T doLoad(Object normalizedNaturalIdValue) { final EffectiveEntityGraph effectiveEntityGraph = session.getLoadQueryInfluencers().applyEntityGraph( rootGraph, graphSemantic); try { + @SuppressWarnings("unchecked") final T loaded = cachedResolution != null ? (T) getIdentifierLoadAccess().load(cachedResolution) : (T) entityPersister().getNaturalIdLoader().load( normalizedNaturalIdValue, this, session ); diff --git a/hibernate-core/src/main/java/org/hibernate/loader/internal/SimpleNaturalIdLoadAccessImpl.java b/hibernate-core/src/main/java/org/hibernate/loader/internal/SimpleNaturalIdLoadAccessImpl.java index 4f3f3016b5a7..d03f29d2d42f 100644 --- a/hibernate-core/src/main/java/org/hibernate/loader/internal/SimpleNaturalIdLoadAccessImpl.java +++ b/hibernate-core/src/main/java/org/hibernate/loader/internal/SimpleNaturalIdLoadAccessImpl.java @@ -36,8 +36,8 @@ public SimpleNaturalIdLoadAccessImpl(LoadAccessContext context, EntityMappingTyp hasSimpleNaturalId = entityDescriptor.getNaturalIdMapping() instanceof SimpleNaturalIdMapping; if ( !hasSimpleNaturalId ) { - // just log it - we allow this for composite natural-ids with the assumption - // that a singular representation of the natural-id (Map or array) will be passed + // Just log it - we allow this for composite natural ids with the assumption + // that a singular representation of the natural id (Map or array) will be passed LoaderLogging.LOADER_LOGGER.debugf( "Entity [%s] did not define a simple natural id", entityDescriptor.getEntityName() diff --git a/hibernate-core/src/main/java/org/hibernate/mapping/BasicValue.java b/hibernate-core/src/main/java/org/hibernate/mapping/BasicValue.java index 2c9c2012bb9a..d3df1d8606e2 100644 --- a/hibernate-core/src/main/java/org/hibernate/mapping/BasicValue.java +++ b/hibernate-core/src/main/java/org/hibernate/mapping/BasicValue.java @@ -637,7 +637,7 @@ private Resolution resolution(BasicJavaType explicitJavaType, JavaType final MetadataBuildingContext context = getBuildingContext(); final TypeDefinition autoAppliedTypeDef = context.getTypeDefinitionRegistry().resolveAutoApplied( castType ); if ( autoAppliedTypeDef != null ) { - log.debug("BasicValue resolution matched auto-applied type-definition"); + log.trace( "BasicValue resolution matched auto-applied type definition" ); return autoAppliedTypeDef.resolve( getTypeParameters(), null, context, this ); } } diff --git a/hibernate-core/src/main/java/org/hibernate/mapping/Table.java b/hibernate-core/src/main/java/org/hibernate/mapping/Table.java index 758cb7af2273..6a8cc3ab1fe6 100644 --- a/hibernate-core/src/main/java/org/hibernate/mapping/Table.java +++ b/hibernate-core/src/main/java/org/hibernate/mapping/Table.java @@ -279,8 +279,8 @@ public void addColumn(Column column) { for ( Column pkColumn : primaryKey.getColumns() ) { if ( pkColumn.getCanonicalName().equals( column.getCanonicalName() ) ) { column.setNullable( false ); - if ( log.isDebugEnabled() ) { - log.debugf( + if ( log.isTraceEnabled() ) { + log.tracef( "Forcing column [%s] to be non-null as it is part of the primary key for table [%s]", column.getCanonicalName(), getNameIdentifier().getCanonicalName() diff --git a/hibernate-core/src/main/java/org/hibernate/metamodel/mapping/internal/BasicValuedCollectionPart.java b/hibernate-core/src/main/java/org/hibernate/metamodel/mapping/internal/BasicValuedCollectionPart.java index f65e5f832b85..603b050e0aa8 100644 --- a/hibernate-core/src/main/java/org/hibernate/metamodel/mapping/internal/BasicValuedCollectionPart.java +++ b/hibernate-core/src/main/java/org/hibernate/metamodel/mapping/internal/BasicValuedCollectionPart.java @@ -260,9 +260,9 @@ public Fetch generateFetch( boolean selected, String resultVariable, DomainResultCreationState creationState) { - if ( ResultsLogger.RESULTS_LOGGER.isDebugEnabled() ) { - ResultsLogger.RESULTS_LOGGER.debugf( - "Generating Fetch for collection-part : `%s` -> `%s`", + if ( ResultsLogger.RESULTS_LOGGER.isTraceEnabled() ) { + ResultsLogger.RESULTS_LOGGER.tracef( + "Generating Fetch for collection-part: `%s` -> `%s`", collectionDescriptor.getRole(), nature.getName() ); diff --git a/hibernate-core/src/main/java/org/hibernate/metamodel/mapping/internal/MappingModelCreationHelper.java b/hibernate-core/src/main/java/org/hibernate/metamodel/mapping/internal/MappingModelCreationHelper.java index d5bdbfe17955..40185ab12259 100644 --- a/hibernate-core/src/main/java/org/hibernate/metamodel/mapping/internal/MappingModelCreationHelper.java +++ b/hibernate-core/src/main/java/org/hibernate/metamodel/mapping/internal/MappingModelCreationHelper.java @@ -1850,9 +1850,9 @@ else if ( !lazy || value instanceof ManyToOne manyToOne && value.isNullable() && manyToOne.isIgnoreNotFound() ) { fetchTiming = FetchTiming.IMMEDIATE; if ( lazy ) { - if ( MAPPING_MODEL_CREATION_MESSAGE_LOGGER.isDebugEnabled() ) { - MAPPING_MODEL_CREATION_MESSAGE_LOGGER.debugf( - "Forcing FetchTiming.IMMEDIATE for to-one association : %s.%s", + if ( MAPPING_MODEL_CREATION_MESSAGE_LOGGER.isTraceEnabled() ) { + MAPPING_MODEL_CREATION_MESSAGE_LOGGER.tracef( + "Forcing FetchTiming.IMMEDIATE for to-one association: %s.%s", declaringType.getNavigableRole(), bootProperty.getName() ); diff --git a/hibernate-core/src/main/java/org/hibernate/metamodel/mapping/internal/MappingModelCreationProcess.java b/hibernate-core/src/main/java/org/hibernate/metamodel/mapping/internal/MappingModelCreationProcess.java index f9d709b5412d..447e093129dd 100644 --- a/hibernate-core/src/main/java/org/hibernate/metamodel/mapping/internal/MappingModelCreationProcess.java +++ b/hibernate-core/src/main/java/org/hibernate/metamodel/mapping/internal/MappingModelCreationProcess.java @@ -99,7 +99,7 @@ private void execute() { } private void executePostInitCallbacks() { - MAPPING_MODEL_CREATION_MESSAGE_LOGGER.debugf( "Starting post-init callbacks" ); + MAPPING_MODEL_CREATION_MESSAGE_LOGGER.tracef( "Starting post-init callbacks" ); Map exceptions = new HashMap<>(); while ( postInitCallbacks != null && !postInitCallbacks.isEmpty() ) { @@ -249,10 +249,10 @@ public PostInitCallbackEntry(String description, PostInitCallback callback) { } private boolean process() { - MAPPING_MODEL_CREATION_MESSAGE_LOGGER.debugf( - "Starting PostInitCallbackEntry : %s", - description - ); +// MAPPING_MODEL_CREATION_MESSAGE_LOGGER.tracef( +// "Starting PostInitCallbackEntry : %s", +// description +// ); return callback.process(); } diff --git a/hibernate-core/src/main/java/org/hibernate/metamodel/mapping/internal/PluralAttributeMappingImpl.java b/hibernate-core/src/main/java/org/hibernate/metamodel/mapping/internal/PluralAttributeMappingImpl.java index 29c84592323d..82946aa30054 100644 --- a/hibernate-core/src/main/java/org/hibernate/metamodel/mapping/internal/PluralAttributeMappingImpl.java +++ b/hibernate-core/src/main/java/org/hibernate/metamodel/mapping/internal/PluralAttributeMappingImpl.java @@ -249,9 +249,9 @@ public void finishInitialization( final TranslationContext context = collectionDescriptor::getFactory; if ( hasOrder ) { - if ( log.isDebugEnabled() ) { - log.debugf( - "Translating order-by fragment [%s] for collection role : %s", + if ( log.isTraceEnabled() ) { + log.tracef( + "Translating order-by fragment [%s] for collection role: %s", bootDescriptor.getOrderBy(), collectionDescriptor.getRole() ); @@ -264,9 +264,9 @@ public void finishInitialization( } if ( hasManyToManyOrder ) { - if ( log.isDebugEnabled() ) { - log.debugf( - "Translating many-to-many order-by fragment [%s] for collection role : %s", + if ( log.isTraceEnabled() ) { + log.tracef( + "Translating many-to-many order-by fragment [%s] for collection role: %s", bootDescriptor.getOrderBy(), collectionDescriptor.getRole() ); diff --git a/hibernate-core/src/main/java/org/hibernate/metamodel/mapping/ordering/ast/PathConsumer.java b/hibernate-core/src/main/java/org/hibernate/metamodel/mapping/ordering/ast/PathConsumer.java index 15bcaba38927..e8dac1055155 100644 --- a/hibernate-core/src/main/java/org/hibernate/metamodel/mapping/ordering/ast/PathConsumer.java +++ b/hibernate-core/src/main/java/org/hibernate/metamodel/mapping/ordering/ast/PathConsumer.java @@ -53,13 +53,13 @@ public void consumeIdentifier( } pathSoFar.append( unquotedIdentifier ); - log.tracef( - "BasicDotIdentifierHandler#consumeIdentifier( %s, %s, %s ) - %s", - unquotedIdentifier, - isBase, - isTerminal, - pathSoFar - ); +// log.tracef( +// "BasicDotIdentifierHandler#consumeIdentifier( %s, %s, %s ) - %s", +// unquotedIdentifier, +// isBase, +// isTerminal, +// pathSoFar +// ); currentPart = currentPart.resolvePathPart( unquotedIdentifier, identifier, isTerminal, translationContext ); } diff --git a/hibernate-core/src/main/java/org/hibernate/metamodel/model/domain/internal/JpaMetamodelImpl.java b/hibernate-core/src/main/java/org/hibernate/metamodel/model/domain/internal/JpaMetamodelImpl.java index 01bf7fd6b2a3..3cd722566eee 100644 --- a/hibernate-core/src/main/java/org/hibernate/metamodel/model/domain/internal/JpaMetamodelImpl.java +++ b/hibernate-core/src/main/java/org/hibernate/metamodel/model/domain/internal/JpaMetamodelImpl.java @@ -388,7 +388,7 @@ private Field getJavaField(String className, String fieldName) throws NoSuchFiel public void addNamedEntityGraph(String graphName, RootGraphImplementor rootGraph) { final EntityGraph old = entityGraphMap.put( graphName, rootGraph.makeImmutableCopy( graphName ) ); if ( old != null ) { - log.debugf( "EntityGraph named '%s' was replaced", graphName ); + log.tracef( "EntityGraph named '%s' was replaced", graphName ); } } @@ -485,11 +485,8 @@ private ImportInfo resolveImport(final String name) { private void applyNamedEntityGraphs(Collection namedEntityGraphs) { for ( NamedEntityGraphDefinition definition : namedEntityGraphs ) { - log.debugf( - "Applying named entity graph [name=%s, source=%s]", - definition.name(), - definition.source() - ); + log.tracef( "Applying named entity graph [name=%s, source=%s]", + definition.name(), definition.source() ); final RootGraphImplementor graph = definition.graphCreator().createEntityGraph( (entityClass) -> { diff --git a/hibernate-core/src/main/java/org/hibernate/persister/collection/AbstractCollectionPersister.java b/hibernate-core/src/main/java/org/hibernate/persister/collection/AbstractCollectionPersister.java index 99ac5afc6a11..775363064d27 100644 --- a/hibernate-core/src/main/java/org/hibernate/persister/collection/AbstractCollectionPersister.java +++ b/hibernate-core/src/main/java/org/hibernate/persister/collection/AbstractCollectionPersister.java @@ -105,7 +105,6 @@ import org.hibernate.sql.ast.tree.select.QuerySpec; import org.hibernate.sql.ast.tree.select.SelectClause; import org.hibernate.sql.ast.tree.select.SelectStatement; -import org.hibernate.sql.model.ModelMutationLogging; import org.hibernate.sql.model.MutationType; import org.hibernate.sql.model.TableMapping; import org.hibernate.sql.model.TableMapping.MutationDetails; @@ -712,30 +711,30 @@ private NamedQueryMemento getNamedQueryMemento(MetadataImplementor bootModel) } protected void logStaticSQL() { - if ( ModelMutationLogging.MODEL_MUTATION_LOGGER.isDebugEnabled() ) { - MODEL_MUTATION_LOGGER.debugf( "Static SQL for collection: %s", getRole() ); + if ( MODEL_MUTATION_LOGGER.isTraceEnabled() ) { + MODEL_MUTATION_LOGGER.tracef( "Static SQL for collection: %s", getRole() ); final JdbcMutationOperation insertRowOperation = getRowMutationOperations().getInsertRowOperation(); final String insertRowSql = insertRowOperation != null ? insertRowOperation.getSqlString() : null; if ( insertRowSql != null ) { - MODEL_MUTATION_LOGGER.debugf( " Row insert: %s", insertRowSql ); + MODEL_MUTATION_LOGGER.tracef( " Row insert: %s", insertRowSql ); } final JdbcMutationOperation updateRowOperation = getRowMutationOperations().getUpdateRowOperation(); final String updateRowSql = updateRowOperation != null ? updateRowOperation.getSqlString() : null; if ( updateRowSql != null ) { - MODEL_MUTATION_LOGGER.debugf( " Row update: %s", updateRowSql ); + MODEL_MUTATION_LOGGER.tracef( " Row update: %s", updateRowSql ); } final JdbcMutationOperation deleteRowOperation = getRowMutationOperations().getDeleteRowOperation(); final String deleteRowSql = deleteRowOperation != null ? deleteRowOperation.getSqlString() : null; if ( deleteRowSql != null ) { - MODEL_MUTATION_LOGGER.debugf( " Row delete: %s", deleteRowSql ); + MODEL_MUTATION_LOGGER.tracef( " Row delete: %s", deleteRowSql ); } final String deleteAllSql = getRemoveCoordinator().getSqlString(); if ( deleteAllSql != null ) { - MODEL_MUTATION_LOGGER.debugf( " One-shot delete: %s", deleteAllSql ); + MODEL_MUTATION_LOGGER.tracef( " One-shot delete: %s", deleteAllSql ); } } } diff --git a/hibernate-core/src/main/java/org/hibernate/persister/collection/BasicCollectionPersister.java b/hibernate-core/src/main/java/org/hibernate/persister/collection/BasicCollectionPersister.java index 1d7ec02b337e..9f4764119335 100644 --- a/hibernate-core/src/main/java/org/hibernate/persister/collection/BasicCollectionPersister.java +++ b/hibernate-core/src/main/java/org/hibernate/persister/collection/BasicCollectionPersister.java @@ -144,8 +144,8 @@ private UpdateRowsCoordinator buildUpdateRowCoordinator() { && !isInverse(); if ( !performUpdates ) { - if ( MODEL_MUTATION_LOGGER.isDebugEnabled() ) { - MODEL_MUTATION_LOGGER.debugf( + if ( MODEL_MUTATION_LOGGER.isTraceEnabled() ) { + MODEL_MUTATION_LOGGER.tracef( "Skipping collection row updates - %s", getRolePath() ); @@ -158,8 +158,8 @@ private UpdateRowsCoordinator buildUpdateRowCoordinator() { private InsertRowsCoordinator buildInsertRowCoordinator() { if ( isInverse() || !isRowInsertEnabled() ) { - if ( MODEL_MUTATION_LOGGER.isDebugEnabled() ) { - MODEL_MUTATION_LOGGER.debugf( + if ( MODEL_MUTATION_LOGGER.isTraceEnabled() ) { + MODEL_MUTATION_LOGGER.tracef( "Skipping collection inserts - %s", getRolePath() ); @@ -172,8 +172,8 @@ private InsertRowsCoordinator buildInsertRowCoordinator() { private DeleteRowsCoordinator buildDeleteRowCoordinator() { if ( ! needsRemove() ) { - if ( MODEL_MUTATION_LOGGER.isDebugEnabled() ) { - MODEL_MUTATION_LOGGER.debugf( + if ( MODEL_MUTATION_LOGGER.isTraceEnabled() ) { + MODEL_MUTATION_LOGGER.tracef( "Skipping collection row deletions - %s", getRolePath() ); @@ -186,8 +186,8 @@ private DeleteRowsCoordinator buildDeleteRowCoordinator() { private RemoveCoordinator buildDeleteAllCoordinator() { if ( ! needsRemove() ) { - if ( MODEL_MUTATION_LOGGER.isDebugEnabled() ) { - MODEL_MUTATION_LOGGER.debugf( + if ( MODEL_MUTATION_LOGGER.isTraceEnabled() ) { + MODEL_MUTATION_LOGGER.tracef( "Skipping collection removals - %s", getRolePath() ); diff --git a/hibernate-core/src/main/java/org/hibernate/persister/collection/OneToManyPersister.java b/hibernate-core/src/main/java/org/hibernate/persister/collection/OneToManyPersister.java index c0846f953d30..b71cd203e6fd 100644 --- a/hibernate-core/src/main/java/org/hibernate/persister/collection/OneToManyPersister.java +++ b/hibernate-core/src/main/java/org/hibernate/persister/collection/OneToManyPersister.java @@ -407,8 +407,8 @@ private RowMutationOperations buildRowMutationOperations() { private InsertRowsCoordinator buildInsertCoordinator() { if ( isInverse() || !isRowInsertEnabled() ) { - if ( MODEL_MUTATION_LOGGER.isDebugEnabled() ) { - MODEL_MUTATION_LOGGER.debugf( "Skipping collection (re)creation - %s", getRolePath() ); + if ( MODEL_MUTATION_LOGGER.isTraceEnabled() ) { + MODEL_MUTATION_LOGGER.tracef( "Skipping collection (re)creation - %s", getRolePath() ); } return new InsertRowsCoordinatorNoOp( this ); } @@ -424,8 +424,8 @@ private InsertRowsCoordinator buildInsertCoordinator() { private UpdateRowsCoordinator buildUpdateCoordinator() { if ( !isRowDeleteEnabled() && !isRowInsertEnabled() ) { - if ( MODEL_MUTATION_LOGGER.isDebugEnabled() ) { - MODEL_MUTATION_LOGGER.debugf( "Skipping collection row updates - %s", getRolePath() ); + if ( MODEL_MUTATION_LOGGER.isTraceEnabled() ) { + MODEL_MUTATION_LOGGER.tracef( "Skipping collection row updates - %s", getRolePath() ); } return new UpdateRowsCoordinatorNoOp( this ); } @@ -440,8 +440,8 @@ private UpdateRowsCoordinator buildUpdateCoordinator() { private DeleteRowsCoordinator buildDeleteCoordinator() { if ( !needsRemove() ) { - if ( MODEL_MUTATION_LOGGER.isDebugEnabled() ) { - MODEL_MUTATION_LOGGER.debugf( "Skipping collection row deletions - %s", getRolePath() ); + if ( MODEL_MUTATION_LOGGER.isTraceEnabled() ) { + MODEL_MUTATION_LOGGER.tracef( "Skipping collection row deletions - %s", getRolePath() ); } return new DeleteRowsCoordinatorNoOp( this ); } @@ -458,8 +458,8 @@ private DeleteRowsCoordinator buildDeleteCoordinator() { private RemoveCoordinator buildDeleteAllCoordinator() { if ( ! needsRemove() ) { - if ( MODEL_MUTATION_LOGGER.isDebugEnabled() ) { - MODEL_MUTATION_LOGGER.debugf( "Skipping collection removals - %s", getRolePath() ); + if ( MODEL_MUTATION_LOGGER.isTraceEnabled() ) { + MODEL_MUTATION_LOGGER.tracef( "Skipping collection removals - %s", getRolePath() ); } return new RemoveCoordinatorNoOp( this ); } diff --git a/hibernate-core/src/main/java/org/hibernate/persister/collection/mutation/AbstractUpdateRowsCoordinator.java b/hibernate-core/src/main/java/org/hibernate/persister/collection/mutation/AbstractUpdateRowsCoordinator.java index 983c6a87e422..7413d03331c1 100644 --- a/hibernate-core/src/main/java/org/hibernate/persister/collection/mutation/AbstractUpdateRowsCoordinator.java +++ b/hibernate-core/src/main/java/org/hibernate/persister/collection/mutation/AbstractUpdateRowsCoordinator.java @@ -46,7 +46,7 @@ public void updateRows(Object key, PersistentCollection collection, SharedSes // update all the modified entries int count = doUpdate( key, collection, session ); - MODEL_MUTATION_LOGGER.debugf( "Updated `%s` collection rows - %s#%s", count, mutationTarget.getRolePath(), key ); + MODEL_MUTATION_LOGGER.tracef( "Updated `%s` collection rows - %s#%s", count, mutationTarget.getRolePath(), key ); } protected abstract int doUpdate(Object key, PersistentCollection collection, SharedSessionContractImplementor session); diff --git a/hibernate-core/src/main/java/org/hibernate/persister/collection/mutation/DeleteRowsCoordinatorStandard.java b/hibernate-core/src/main/java/org/hibernate/persister/collection/mutation/DeleteRowsCoordinatorStandard.java index 3d8f8f536523..9e21a7df0897 100644 --- a/hibernate-core/src/main/java/org/hibernate/persister/collection/mutation/DeleteRowsCoordinatorStandard.java +++ b/hibernate-core/src/main/java/org/hibernate/persister/collection/mutation/DeleteRowsCoordinatorStandard.java @@ -59,8 +59,8 @@ public void deleteRows(PersistentCollection collection, Object key, SharedSes operationGroup = createOperationGroup(); } - if ( MODEL_MUTATION_LOGGER.isDebugEnabled() ) { - MODEL_MUTATION_LOGGER.debugf( + if ( MODEL_MUTATION_LOGGER.isTraceEnabled() ) { + MODEL_MUTATION_LOGGER.tracef( "Deleting removed collection rows - %s : %s", mutationTarget.getRolePath(), key @@ -80,7 +80,7 @@ public void deleteRows(PersistentCollection collection, Object key, SharedSes final Iterator deletes = collection.getDeletes( collectionDescriptor, !deleteByIndex ); if ( !deletes.hasNext() ) { - MODEL_MUTATION_LOGGER.debug( "No rows to delete" ); + MODEL_MUTATION_LOGGER.trace( "No rows to delete" ); return; } @@ -105,7 +105,8 @@ public void deleteRows(PersistentCollection collection, Object key, SharedSes deletionCount++; } - MODEL_MUTATION_LOGGER.debugf( "Done deleting `%s` collection rows : %s", deletionCount, mutationTarget.getRolePath() ); + MODEL_MUTATION_LOGGER.tracef( "Done deleting `%s` collection rows : %s", + deletionCount, mutationTarget.getRolePath() ); } finally { mutationExecutor.release(); diff --git a/hibernate-core/src/main/java/org/hibernate/persister/collection/mutation/DeleteRowsCoordinatorTablePerSubclass.java b/hibernate-core/src/main/java/org/hibernate/persister/collection/mutation/DeleteRowsCoordinatorTablePerSubclass.java index 0d4707948c91..820f4345a88b 100644 --- a/hibernate-core/src/main/java/org/hibernate/persister/collection/mutation/DeleteRowsCoordinatorTablePerSubclass.java +++ b/hibernate-core/src/main/java/org/hibernate/persister/collection/mutation/DeleteRowsCoordinatorTablePerSubclass.java @@ -55,8 +55,8 @@ public CollectionMutationTarget getMutationTarget() { @Override public void deleteRows(PersistentCollection collection, Object key, SharedSessionContractImplementor session) { - if ( MODEL_MUTATION_LOGGER.isDebugEnabled() ) { - MODEL_MUTATION_LOGGER.debugf( + if ( MODEL_MUTATION_LOGGER.isTraceEnabled() ) { + MODEL_MUTATION_LOGGER.tracef( "Deleting removed collection rows - %s : %s", mutationTarget.getRolePath(), key @@ -68,7 +68,7 @@ public void deleteRows(PersistentCollection collection, Object key, SharedSes final Iterator deletes = collection.getDeletes( collectionDescriptor, !deleteByIndex ); if ( !deletes.hasNext() ) { - MODEL_MUTATION_LOGGER.debug( "No rows to delete" ); + MODEL_MUTATION_LOGGER.trace( "No rows to delete" ); return; } final MutationExecutor[] executors = new MutationExecutor[subclassEntries.length]; @@ -108,7 +108,8 @@ public void deleteRows(PersistentCollection collection, Object key, SharedSes deletionCount++; } - MODEL_MUTATION_LOGGER.debugf( "Done deleting `%s` collection rows : %s", deletionCount, mutationTarget.getRolePath() ); + MODEL_MUTATION_LOGGER.tracef( "Done deleting `%s` collection rows : %s", + deletionCount, mutationTarget.getRolePath() ); } finally { for ( MutationExecutor executor : executors ) { @@ -125,7 +126,8 @@ private SubclassEntry getSubclassEntry(EntityPersister elementPersister) { if ( subclassEntry != null ) { return subclassEntry; } - final BasicBatchKey basicBatchKey = new BasicBatchKey( mutationTarget.getRolePath() + "#DELETE#" + subclassId ); + final BasicBatchKey basicBatchKey = + new BasicBatchKey( mutationTarget.getRolePath() + "#DELETE#" + subclassId ); return subclassEntries[subclassId] = new SubclassEntry( () -> basicBatchKey, createOperationGroup( elementPersister ) diff --git a/hibernate-core/src/main/java/org/hibernate/persister/collection/mutation/InsertRowsCoordinatorStandard.java b/hibernate-core/src/main/java/org/hibernate/persister/collection/mutation/InsertRowsCoordinatorStandard.java index 9a6b3db1376f..df3f08f22814 100644 --- a/hibernate-core/src/main/java/org/hibernate/persister/collection/mutation/InsertRowsCoordinatorStandard.java +++ b/hibernate-core/src/main/java/org/hibernate/persister/collection/mutation/InsertRowsCoordinatorStandard.java @@ -65,8 +65,8 @@ public void insertRows( operationGroup = createOperationGroup(); } - if ( MODEL_MUTATION_LOGGER.isDebugEnabled() ) { - MODEL_MUTATION_LOGGER.debugf( + if ( MODEL_MUTATION_LOGGER.isTraceEnabled() ) { + MODEL_MUTATION_LOGGER.tracef( "Inserting collection rows - %s : %s", mutationTarget.getRolePath(), id @@ -87,7 +87,7 @@ public void insertRows( final Iterator entries = collection.entries( collectionDescriptor ); collection.preInsert( collectionDescriptor ); if ( !entries.hasNext() ) { - MODEL_MUTATION_LOGGER.debugf( + MODEL_MUTATION_LOGGER.tracef( "No collection rows to insert - %s : %s", mutationTarget.getRolePath(), id @@ -118,7 +118,8 @@ public void insertRows( entryCount++; } - MODEL_MUTATION_LOGGER.debugf( "Done inserting `%s` collection rows : %s", entryCount, mutationTarget.getRolePath() ); + MODEL_MUTATION_LOGGER.tracef( "Done inserting `%s` collection rows : %s", + entryCount, mutationTarget.getRolePath() ); } finally { diff --git a/hibernate-core/src/main/java/org/hibernate/persister/collection/mutation/InsertRowsCoordinatorTablePerSubclass.java b/hibernate-core/src/main/java/org/hibernate/persister/collection/mutation/InsertRowsCoordinatorTablePerSubclass.java index 52f729e68fe0..1f5cb4032f82 100644 --- a/hibernate-core/src/main/java/org/hibernate/persister/collection/mutation/InsertRowsCoordinatorTablePerSubclass.java +++ b/hibernate-core/src/main/java/org/hibernate/persister/collection/mutation/InsertRowsCoordinatorTablePerSubclass.java @@ -41,10 +41,11 @@ public InsertRowsCoordinatorTablePerSubclass( ServiceRegistry serviceRegistry) { this.mutationTarget = mutationTarget; this.rowMutationOperations = rowMutationOperations; - this.subclassEntries = new SubclassEntry[mutationTarget.getElementPersister() - .getRootEntityDescriptor() - .getSubclassEntityNames() - .size()]; + this.subclassEntries = + new SubclassEntry[mutationTarget.getElementPersister() + .getRootEntityDescriptor() + .getSubclassEntityNames() + .size()]; this.mutationExecutorService = serviceRegistry.getService( MutationExecutorService.class ); } @@ -64,9 +65,9 @@ public void insertRows( Object id, EntryFilter entryChecker, SharedSessionContractImplementor session) { - final boolean loggerDebugEnabled = MODEL_MUTATION_LOGGER.isDebugEnabled(); - if ( loggerDebugEnabled ) { - MODEL_MUTATION_LOGGER.debugf( + final boolean loggerTraceEnabled = MODEL_MUTATION_LOGGER.isTraceEnabled(); + if ( loggerTraceEnabled ) { + MODEL_MUTATION_LOGGER.tracef( "Inserting collection rows - %s : %s", mutationTarget.getRolePath(), id @@ -79,8 +80,8 @@ public void insertRows( final Iterator entries = collection.entries( collectionDescriptor ); collection.preInsert( collectionDescriptor ); if ( !entries.hasNext() ) { - if ( loggerDebugEnabled ) { - MODEL_MUTATION_LOGGER.debugf( + if ( loggerTraceEnabled ) { + MODEL_MUTATION_LOGGER.tracef( "No collection rows to insert - %s : %s", mutationTarget.getRolePath(), id @@ -124,9 +125,9 @@ public void insertRows( entryCount++; } - if ( loggerDebugEnabled ) { - MODEL_MUTATION_LOGGER.debugf( - "Done inserting `%s` collection rows : %s", + if ( loggerTraceEnabled ) { + MODEL_MUTATION_LOGGER.tracef( + "Done inserting `%s` collection rows: %s", entryCount, mutationTarget.getRolePath() ); @@ -148,7 +149,8 @@ private SubclassEntry getSubclassEntry(EntityPersister elementPersister) { if ( subclassEntry != null ) { return subclassEntry; } - final BasicBatchKey basicBatchKey = new BasicBatchKey( mutationTarget.getRolePath() + "#INSERT#" + subclassId ); + final BasicBatchKey basicBatchKey = + new BasicBatchKey( mutationTarget.getRolePath() + "#INSERT#" + subclassId ); return subclassEntries[subclassId] = new SubclassEntry( () -> basicBatchKey, createOperationGroup( elementPersister ) diff --git a/hibernate-core/src/main/java/org/hibernate/persister/collection/mutation/RemoveCoordinatorStandard.java b/hibernate-core/src/main/java/org/hibernate/persister/collection/mutation/RemoveCoordinatorStandard.java index cd364f10fc5b..7754abc0eac5 100644 --- a/hibernate-core/src/main/java/org/hibernate/persister/collection/mutation/RemoveCoordinatorStandard.java +++ b/hibernate-core/src/main/java/org/hibernate/persister/collection/mutation/RemoveCoordinatorStandard.java @@ -72,8 +72,8 @@ public String getSqlString() { @Override public void deleteAllRows(Object key, SharedSessionContractImplementor session) { - if ( MODEL_MUTATION_LOGGER.isDebugEnabled() ) { - MODEL_MUTATION_LOGGER.debugf( + if ( MODEL_MUTATION_LOGGER.isTraceEnabled() ) { + MODEL_MUTATION_LOGGER.tracef( "Deleting collection - %s : %s", mutationTarget.getRolePath(), key @@ -121,7 +121,8 @@ private MutationOperationGroup buildOperationGroup() { assert mutationTarget.getTargetPart().getKeyDescriptor() != null; if ( MODEL_MUTATION_LOGGER.isTraceEnabled() ) { - MODEL_MUTATION_LOGGER.tracef( "Starting RemoveCoordinator#buildOperationGroup - %s", mutationTarget.getRolePath() ); + MODEL_MUTATION_LOGGER.tracef( "Starting RemoveCoordinator#buildOperationGroup - %s", + mutationTarget.getRolePath() ); } final CollectionTableMapping tableMapping = mutationTarget.getCollectionTableMapping(); diff --git a/hibernate-core/src/main/java/org/hibernate/persister/collection/mutation/RemoveCoordinatorTablePerSubclass.java b/hibernate-core/src/main/java/org/hibernate/persister/collection/mutation/RemoveCoordinatorTablePerSubclass.java index c73034e11559..b0cb515d6a42 100644 --- a/hibernate-core/src/main/java/org/hibernate/persister/collection/mutation/RemoveCoordinatorTablePerSubclass.java +++ b/hibernate-core/src/main/java/org/hibernate/persister/collection/mutation/RemoveCoordinatorTablePerSubclass.java @@ -63,8 +63,8 @@ public String getSqlString() { @Override public void deleteAllRows(Object key, SharedSessionContractImplementor session) { - if ( MODEL_MUTATION_LOGGER.isDebugEnabled() ) { - MODEL_MUTATION_LOGGER.debugf( + if ( MODEL_MUTATION_LOGGER.isTraceEnabled() ) { + MODEL_MUTATION_LOGGER.tracef( "Deleting collection - %s : %s", mutationTarget.getRolePath(), key @@ -127,7 +127,8 @@ private MutationOperationGroup buildOperationGroup(EntityPersister elementPersis assert mutationTarget.getTargetPart().getKeyDescriptor() != null; if ( MODEL_MUTATION_LOGGER.isTraceEnabled() ) { - MODEL_MUTATION_LOGGER.tracef( "Starting RemoveCoordinator#buildOperationGroup - %s", mutationTarget.getRolePath() ); + MODEL_MUTATION_LOGGER.tracef( "Starting RemoveCoordinator#buildOperationGroup - %s", + mutationTarget.getRolePath() ); } final CollectionTableMapping collectionTableMapping = mutationTarget.getCollectionTableMapping(); diff --git a/hibernate-core/src/main/java/org/hibernate/persister/entity/JoinedSubclassEntityPersister.java b/hibernate-core/src/main/java/org/hibernate/persister/entity/JoinedSubclassEntityPersister.java index 7e73a464e72a..ffd90a73533b 100644 --- a/hibernate-core/src/main/java/org/hibernate/persister/entity/JoinedSubclassEntityPersister.java +++ b/hibernate-core/src/main/java/org/hibernate/persister/entity/JoinedSubclassEntityPersister.java @@ -171,7 +171,7 @@ public JoinedSubclassEntityPersister( forceDiscriminator = persistentClass.isForceDiscriminator(); final Value discriminatorMapping = persistentClass.getDiscriminator(); if ( discriminatorMapping != null ) { - log.debug( "Encountered explicit discriminator mapping for joined inheritance" ); + log.tracef( "Encountered explicit discriminator mapping for joined inheritance" ); final Selectable selectable = discriminatorMapping.getSelectables().get(0); if ( selectable instanceof Column column ) { explicitDiscriminatorColumnName = column.getQuotedName( dialect ); diff --git a/hibernate-core/src/main/java/org/hibernate/persister/entity/mutation/AbstractMutationCoordinator.java b/hibernate-core/src/main/java/org/hibernate/persister/entity/mutation/AbstractMutationCoordinator.java index d909c9e81c77..240af8e19dd5 100644 --- a/hibernate-core/src/main/java/org/hibernate/persister/entity/mutation/AbstractMutationCoordinator.java +++ b/hibernate-core/src/main/java/org/hibernate/persister/entity/mutation/AbstractMutationCoordinator.java @@ -18,7 +18,6 @@ import org.hibernate.metamodel.mapping.AttributeMapping; import org.hibernate.metamodel.mapping.AttributeMappingsList; import org.hibernate.persister.entity.EntityPersister; -import org.hibernate.sql.model.ModelMutationLogging; import org.hibernate.sql.model.MutationOperation; import org.hibernate.sql.model.MutationOperationGroup; import org.hibernate.sql.model.ValuesAnalysis; @@ -29,6 +28,8 @@ import org.hibernate.sql.model.ast.builder.RestrictedTableMutationBuilder; import org.hibernate.sql.model.internal.MutationOperationGroupFactory; +import static org.hibernate.sql.model.ModelMutationLogging.MODEL_MUTATION_LOGGER; + /** * Base support for coordinating mutations against an entity * @@ -99,7 +100,7 @@ protected MutationOperationGroup createOperationGroup(ValuesAnalysis valuesAnaly } else { skipped++; - ModelMutationLogging.MODEL_MUTATION_LOGGER.debugf( + MODEL_MUTATION_LOGGER.tracef( "Skipping table update - %s", tableMutation.getTableName() ); diff --git a/hibernate-core/src/main/java/org/hibernate/query/hql/internal/BasicDotIdentifierConsumer.java b/hibernate-core/src/main/java/org/hibernate/query/hql/internal/BasicDotIdentifierConsumer.java index 8ffb373337cc..ac9146e5ca0d 100644 --- a/hibernate-core/src/main/java/org/hibernate/query/hql/internal/BasicDotIdentifierConsumer.java +++ b/hibernate-core/src/main/java/org/hibernate/query/hql/internal/BasicDotIdentifierConsumer.java @@ -80,13 +80,13 @@ public void consumeIdentifier(String identifier, boolean isBase, boolean isTermi } pathSoFar.append( identifier ); - QUERY_LOGGER.tracef( - "BasicDotIdentifierHandler#consumeIdentifier( %s, %s, %s ) - %s", - identifier, - isBase, - isTerminal, - pathSoFar - ); +// QUERY_LOGGER.tracef( +// "BasicDotIdentifierHandler#consumeIdentifier( %s, %s, %s ) - %s", +// identifier, +// isBase, +// isTerminal, +// pathSoFar +// ); currentPart = currentPart.resolvePathPart( identifier, isTerminal, creationState ); } @@ -121,13 +121,13 @@ public SemanticPathPart resolvePathPart( String identifier, boolean isTerminal, SqmCreationState creationState) { - QUERY_LOGGER.tracef( - "BaseLocalSequencePart#consumeIdentifier( %s, %s, %s ) - %s", - identifier, - isBase, - isTerminal, - pathSoFar - ); +// QUERY_LOGGER.tracef( +// "BaseLocalSequencePart#consumeIdentifier( %s, %s, %s ) - %s", +// identifier, +// isBase, +// isTerminal, +// pathSoFar +// ); if ( isBase ) { isBase = false; diff --git a/hibernate-core/src/main/java/org/hibernate/query/hql/internal/QualifiedJoinPathConsumer.java b/hibernate-core/src/main/java/org/hibernate/query/hql/internal/QualifiedJoinPathConsumer.java index 3b9e8f4711b1..d09b48affd62 100644 --- a/hibernate-core/src/main/java/org/hibernate/query/hql/internal/QualifiedJoinPathConsumer.java +++ b/hibernate-core/src/main/java/org/hibernate/query/hql/internal/QualifiedJoinPathConsumer.java @@ -355,7 +355,7 @@ public void consumeIdentifier(String identifier, boolean isTerminal, boolean all assert ! ( joinedEntityType instanceof SqmPolymorphicRootDescriptor ); if ( fetch ) { - log.debugf( "Ignoring fetch on entity join : %s(%s)", joinedEntityType.getHibernateEntityName(), alias ); + log.debugf( "Ignoring fetch on entity join: %s(%s)", joinedEntityType.getHibernateEntityName(), alias ); } join = new SqmEntityJoin<>( joinedEntityType, alias, joinType, sqmRoot ); diff --git a/hibernate-core/src/main/java/org/hibernate/query/hql/internal/SemanticQueryBuilder.java b/hibernate-core/src/main/java/org/hibernate/query/hql/internal/SemanticQueryBuilder.java index 5e765f1dcdb7..db5f9b58e394 100644 --- a/hibernate-core/src/main/java/org/hibernate/query/hql/internal/SemanticQueryBuilder.java +++ b/hibernate-core/src/main/java/org/hibernate/query/hql/internal/SemanticQueryBuilder.java @@ -1719,7 +1719,7 @@ private SqmSortSpecification visitSortSpecification( query ); } if ( sortExpression instanceof SqmLiteral || sortExpression instanceof SqmParameter ) { - HqlLogging.QUERY_LOGGER.debugf( "Questionable sorting by constant value : %s", sortExpression ); + HqlLogging.QUERY_LOGGER.debugf( "Questionable sorting by constant value: %s", sortExpression ); } return new SqmSortSpecification( sortExpression, sortOrder( ctx ), nullPrecedence( ctx ) ); } @@ -2145,7 +2145,7 @@ public final SqmCrossJoin visitCrossJoin(HqlParser.CrossJoinContext ctx) { protected void consumeCrossJoin(HqlParser.CrossJoinContext parserJoin, SqmRoot sqmRoot) { final String name = getEntityName( parserJoin.entityName() ); - SqmTreeCreationLogger.LOGGER.debugf( "Handling root path - %s", name ); + SqmTreeCreationLogger.LOGGER.tracef( "Handling root path - %s", name ); final EntityDomainType entityDescriptor = getJpaMetamodel().resolveHqlEntityReference( name ); diff --git a/hibernate-core/src/main/java/org/hibernate/query/hql/internal/SqmPathRegistryImpl.java b/hibernate-core/src/main/java/org/hibernate/query/hql/internal/SqmPathRegistryImpl.java index a08d1f513570..eabb0264f47b 100644 --- a/hibernate-core/src/main/java/org/hibernate/query/hql/internal/SqmPathRegistryImpl.java +++ b/hibernate-core/src/main/java/org/hibernate/query/hql/internal/SqmPathRegistryImpl.java @@ -14,13 +14,11 @@ import org.hibernate.jpa.spi.JpaCompliance; import org.hibernate.metamodel.model.domain.BasicDomainType; import org.hibernate.query.SemanticException; -import org.hibernate.query.hql.HqlLogging; import org.hibernate.query.hql.spi.SqmCreationProcessingState; import org.hibernate.query.hql.spi.SqmPathRegistry; import org.hibernate.query.sqm.AliasCollisionException; import org.hibernate.query.sqm.ParsingException; import org.hibernate.query.sqm.SqmPathSource; -import org.hibernate.query.sqm.SqmTreeCreationLogger; import org.hibernate.query.sqm.tree.domain.SqmPath; import org.hibernate.query.sqm.tree.from.SqmEntityJoin; import org.hibernate.query.sqm.tree.from.SqmFrom; @@ -56,7 +54,6 @@ public SqmPathRegistryImpl(SqmCreationProcessingState associatedProcessingState) @Override public void register(SqmPath sqmPath) { - SqmTreeCreationLogger.LOGGER.tracef( "SqmProcessingIndex#register(SqmPath) : %s", sqmPath.getNavigablePath() ); // Generally we: // 1) add the path to the path-by-path map @@ -261,7 +258,7 @@ else if ( parentRegistered instanceof Join join ) { // (configurable?) option would be to simply pick the first one as a perf optimization SqmFrom found = null; - for ( Map.Entry> entry : sqmFromByPath.entrySet() ) { + for ( var entry : sqmFromByPath.entrySet() ) { final SqmFrom fromElement = entry.getValue(); if ( definesAttribute( fromElement.getReferencedPathSource(), navigableName ) ) { if ( found != null ) { @@ -274,18 +271,18 @@ else if ( parentRegistered instanceof Join join ) { if ( found == null ) { if ( associatedProcessingState.getParentProcessingState() != null ) { - HqlLogging.QUERY_LOGGER.debugf( - "Unable to resolve unqualified attribute [%s] in local from-clause; checking parent ", - navigableName - ); +// QUERY_LOGGER.tracef( +// "Unable to resolve unqualified attribute [%s] in local from-clause; checking parent ", +// navigableName +// ); found = associatedProcessingState.getParentProcessingState().getPathRegistry().findFromExposing( navigableName ); } } - HqlLogging.QUERY_LOGGER.debugf( - "Unable to resolve unqualified attribute [%s] in local from-clause", - navigableName - ); +// QUERY_LOGGER.tracef( +// "Unable to resolve unqualified attribute [%s] in local from-clause", +// navigableName +// ); //noinspection unchecked return (X) found; @@ -293,8 +290,6 @@ else if ( parentRegistered instanceof Join join ) { @Override public > X resolveFrom(NavigablePath navigablePath, Function> creator) { - SqmTreeCreationLogger.LOGGER.tracef( "SqmProcessingIndex#resolvePath(NavigablePath) : %s", navigablePath ); - final SqmFrom existing = sqmFromByPath.get( navigablePath ); if ( existing != null ) { //noinspection unchecked @@ -309,8 +304,6 @@ else if ( parentRegistered instanceof Join join ) { @Override public > X resolveFrom(SqmPath path) { - SqmTreeCreationLogger.LOGGER.tracef( "SqmProcessingIndex#resolvePath(SqmPath) : %s", path ); - final SqmFrom existing = sqmFromByPath.get( path.getNavigablePath() ); if ( existing != null ) { //noinspection unchecked diff --git a/hibernate-core/src/main/java/org/hibernate/query/hql/internal/SqmTreeCreationHelper.java b/hibernate-core/src/main/java/org/hibernate/query/hql/internal/SqmTreeCreationHelper.java index 691749f553a4..2e71a0dac7c5 100644 --- a/hibernate-core/src/main/java/org/hibernate/query/hql/internal/SqmTreeCreationHelper.java +++ b/hibernate-core/src/main/java/org/hibernate/query/hql/internal/SqmTreeCreationHelper.java @@ -139,7 +139,7 @@ public static void handleRootAsCrossJoin( //noinspection unchecked final SqmRoot sqmRoot = (SqmRoot) fromRootContext.accept( sqmBuilder ); - SqmTreeCreationLogger.LOGGER.debugf( "Handling secondary root path as cross-join - %s", sqmRoot.getEntityName() ); + SqmTreeCreationLogger.LOGGER.tracef( "Handling secondary root path as cross-join - %s", sqmRoot.getEntityName() ); final SqmEntityJoin pseudoCrossJoin = new SqmEntityJoin<>( sqmRoot.getManagedType(), extractAlias( fromRootContext.variable(), sqmBuilder ), diff --git a/hibernate-core/src/main/java/org/hibernate/query/hql/internal/StandardHqlTranslator.java b/hibernate-core/src/main/java/org/hibernate/query/hql/internal/StandardHqlTranslator.java index 82e5303f3ba9..150e4619c9dd 100644 --- a/hibernate-core/src/main/java/org/hibernate/query/hql/internal/StandardHqlTranslator.java +++ b/hibernate-core/src/main/java/org/hibernate/query/hql/internal/StandardHqlTranslator.java @@ -14,7 +14,6 @@ import org.hibernate.query.sqm.PathElementException; import org.hibernate.query.SyntaxException; import org.hibernate.query.sqm.TerminalPathException; -import org.hibernate.query.hql.HqlLogging; import org.hibernate.query.hql.HqlTranslator; import org.hibernate.query.hql.spi.SqmCreationOptions; import org.hibernate.query.sqm.InterpretationException; @@ -35,6 +34,7 @@ import org.antlr.v4.runtime.misc.ParseCancellationException; import static java.util.stream.Collectors.toList; +import static org.hibernate.query.hql.HqlLogging.QUERY_LOGGER; /** * Standard implementation of {@link HqlTranslator}. @@ -55,7 +55,7 @@ public StandardHqlTranslator( @Override public SqmStatement translate(String query, Class expectedResultType) { - HqlLogging.QUERY_LOGGER.debugf( "HQL : %s", query ); + QUERY_LOGGER.tracef( "HQL: %s", query ); final HqlParser.StatementContext hqlParseTree = parseHql( query ); diff --git a/hibernate-core/src/main/java/org/hibernate/query/internal/NamedObjectRepositoryImpl.java b/hibernate-core/src/main/java/org/hibernate/query/internal/NamedObjectRepositoryImpl.java index 4eb252765d24..c80f0470880d 100644 --- a/hibernate-core/src/main/java/org/hibernate/query/internal/NamedObjectRepositoryImpl.java +++ b/hibernate-core/src/main/java/org/hibernate/query/internal/NamedObjectRepositoryImpl.java @@ -321,12 +321,12 @@ public Map checkNamedQueries(QueryEngine queryEngine final QueryInterpretationCache interpretationCache = queryEngine.getInterpretationCache(); // Check named HQL queries - log.debugf( "Checking %s named HQL queries", sqmMementoMap.size() ); + log.tracef( "Checking %s named HQL queries", sqmMementoMap.size() ); for ( NamedSqmQueryMemento hqlMemento : sqmMementoMap.values() ) { final String queryString = hqlMemento.getHqlString(); final String registrationName = hqlMemento.getRegistrationName(); try { - log.debugf( "Checking named HQL query: %s", registrationName ); + log.tracef( "Checking named HQL query: %s", registrationName ); interpretationCache.resolveHqlInterpretation( queryString, null, @@ -345,12 +345,12 @@ public Map checkNamedQueries(QueryEngine queryEngine } // Check native-sql queries - log.debugf( "Checking %s named SQL queries", sqlMementoMap.size() ); - for ( NamedNativeQueryMemento memento : sqlMementoMap.values() ) { + log.tracef( "Checking %s named SQL queries", sqlMementoMap.size() ); + for ( var memento : sqlMementoMap.values() ) { memento.validate( queryEngine ); // // this will throw an error if there's something wrong. // try { -// log.debugf( "Checking named SQL query: %s", memento.getRegistrationName() ); +// log.tracef( "Checking named SQL query: %s", memento.getRegistrationName() ); // // TODO : would be really nice to cache the spec on the query-def so as to not have to re-calc the hash; // // currently not doable though because of the resultset-ref stuff... // NativeSQLQuerySpecification spec; diff --git a/hibernate-core/src/main/java/org/hibernate/query/internal/QueryInterpretationCacheStandardImpl.java b/hibernate-core/src/main/java/org/hibernate/query/internal/QueryInterpretationCacheStandardImpl.java index c7cdc6d427bb..14c0e646ca86 100644 --- a/hibernate-core/src/main/java/org/hibernate/query/internal/QueryInterpretationCacheStandardImpl.java +++ b/hibernate-core/src/main/java/org/hibernate/query/internal/QueryInterpretationCacheStandardImpl.java @@ -47,7 +47,7 @@ public class QueryInterpretationCacheStandardImpl implements QueryInterpretation private StatisticsImplementor statistics; public QueryInterpretationCacheStandardImpl(int maxQueryPlanCount, ServiceRegistry serviceRegistry) { - log.debugf( "Starting QueryInterpretationCache(%s)", maxQueryPlanCount ); + log.tracef( "Starting QueryInterpretationCache (size %s)", maxQueryPlanCount ); final InternalCacheFactory cacheFactory = serviceRegistry.requireService( InternalCacheFactory.class ); this.queryPlanCache = cacheFactory.createInternalCache( maxQueryPlanCount ); this.hqlInterpretationCache = cacheFactory.createInternalCache( maxQueryPlanCount ); @@ -76,7 +76,7 @@ private StatisticsImplementor getStatistics() { public SelectQueryPlan resolveSelectQueryPlan( Key key, Supplier> creator) { - log.tracef( "QueryPlan#getSelectQueryPlan(%s)", key ); + log.tracef( "Resolving cached QueryPlan for [%s]", key ); final StatisticsImplementor statistics = getStatistics(); final boolean stats = statistics.isStatisticsEnabled(); @@ -99,13 +99,11 @@ public SelectQueryPlan resolveSelectQueryPlan( @Override public NonSelectQueryPlan getNonSelectQueryPlan(Key key) { - log.tracef( "QueryPlan#getNonSelectQueryPlan(%s)", key ); return null; } @Override public void cacheNonSelectQueryPlan(Key key, NonSelectQueryPlan plan) { - log.tracef( "QueryPlan#cacheNonSelectQueryPlan(%s)", key ); } @Override @@ -113,7 +111,7 @@ public HqlInterpretation resolveHqlInterpretation( String queryString, Class expectedResultType, HqlTranslator translator) { - log.tracef( "QueryPlan#resolveHqlInterpretation( `%s` )", queryString ); + log.tracef( "Resolving HQL interpretation for '%s'", queryString ); final StatisticsImplementor statistics = getStatistics(); final Object cacheKey = expectedResultType != null @@ -184,15 +182,8 @@ protected static HqlInterpretation createHqlInterpretation( public ParameterInterpretation resolveNativeQueryParameters( String queryString, Function creator) { - log.tracef( "QueryPlan#resolveNativeQueryParameters(%s)", queryString ); - return nativeQueryParamCache.computeIfAbsent( - queryString, - s -> { - final ParameterInterpretation interpretation = creator.apply( queryString ); - log.debugf( "Creating and caching NativeQuery ParameterInterpretation - %s", interpretation ); - return interpretation; - } - ); + log.tracef( "Resolving native query parameters for '%s'", queryString ); + return nativeQueryParamCache.computeIfAbsent( queryString, creator ); } @Override @@ -202,7 +193,7 @@ public boolean isEnabled() { @Override public void close() { - log.debug( "Closing QueryInterpretationCache" ); + log.trace( "Closing QueryInterpretationCache" ); hqlInterpretationCache.clear(); nativeQueryParamCache.clear(); queryPlanCache.clear(); diff --git a/hibernate-core/src/main/java/org/hibernate/query/internal/ResultMementoEntityStandard.java b/hibernate-core/src/main/java/org/hibernate/query/internal/ResultMementoEntityStandard.java index d729339baed4..901816a8fea6 100644 --- a/hibernate-core/src/main/java/org/hibernate/query/internal/ResultMementoEntityStandard.java +++ b/hibernate-core/src/main/java/org/hibernate/query/internal/ResultMementoEntityStandard.java @@ -12,7 +12,6 @@ import org.hibernate.metamodel.mapping.EntityMappingType; import org.hibernate.query.results.FetchBuilderBasicValued; import org.hibernate.spi.NavigablePath; -import org.hibernate.query.QueryLogging; import org.hibernate.query.named.FetchMemento; import org.hibernate.query.named.FetchMementoBasic; import org.hibernate.query.named.ResultMementoEntity; @@ -21,6 +20,8 @@ import org.hibernate.query.results.internal.complete.CompleteResultBuilderEntityStandard; import org.hibernate.sql.results.graph.Fetchable; +import static org.hibernate.query.QueryLogging.QUERY_LOGGER; + /** * @author Steve Ebersole */ @@ -45,10 +46,7 @@ public ResultMementoEntityStandard( this.discriminatorMemento = discriminatorMemento; this.fetchMementoMap = fetchMementoMap; - QueryLogging.QUERY_LOGGER.debugf( - "Created ResultMementoEntityStandard - %s", - navigablePath - ); + QUERY_LOGGER.debugf( "Created ResultMementoEntityStandard - %s", navigablePath ); } @Override diff --git a/hibernate-core/src/main/java/org/hibernate/query/results/internal/DomainResultCreationStateImpl.java b/hibernate-core/src/main/java/org/hibernate/query/results/internal/DomainResultCreationStateImpl.java index e7b75c363582..afbc47dce74d 100644 --- a/hibernate-core/src/main/java/org/hibernate/query/results/internal/DomainResultCreationStateImpl.java +++ b/hibernate-core/src/main/java/org/hibernate/query/results/internal/DomainResultCreationStateImpl.java @@ -31,7 +31,6 @@ import org.hibernate.sql.ast.tree.expression.ColumnReference; import org.hibernate.sql.ast.tree.expression.Expression; import org.hibernate.sql.ast.tree.from.TableGroup; -import org.hibernate.sql.results.ResultsLogger; import org.hibernate.sql.results.graph.DomainResultCreationState; import org.hibernate.sql.results.graph.Fetch; import org.hibernate.sql.results.graph.FetchParent; @@ -49,6 +48,7 @@ import java.util.function.Function; import static org.hibernate.query.results.internal.ResultsHelper.attributeName; +import static org.hibernate.sql.results.ResultsLogger.RESULTS_LOGGER; /** * Central implementation of {@linkplain DomainResultCreationState}, @@ -115,7 +115,7 @@ public boolean arePositionalSelectionsAllowed() { } public void disallowPositionalSelections() { - ResultsLogger.RESULTS_LOGGER.debugf( "Disallowing positional selections : %s", stateIdentifier ); + RESULTS_LOGGER.debugf( "Disallowing positional selections: %s", stateIdentifier ); this.allowPositionalSelections = false; } diff --git a/hibernate-core/src/main/java/org/hibernate/query/spi/AbstractQueryParameter.java b/hibernate-core/src/main/java/org/hibernate/query/spi/AbstractQueryParameter.java index c18704a307de..d9ed101570bc 100644 --- a/hibernate-core/src/main/java/org/hibernate/query/spi/AbstractQueryParameter.java +++ b/hibernate-core/src/main/java/org/hibernate/query/spi/AbstractQueryParameter.java @@ -32,7 +32,7 @@ public AbstractQueryParameter(boolean allowMultiValuedBinding, BindableType a @Override public void disallowMultiValuedBinding() { - QUERY_MESSAGE_LOGGER.debugf( "QueryParameter#disallowMultiValuedBinding() called : %s", this ); + QUERY_MESSAGE_LOGGER.debugf( "QueryParameter#disallowMultiValuedBinding() called: %s", this ); this.allowMultiValuedBinding = true; } diff --git a/hibernate-core/src/main/java/org/hibernate/query/spi/MutableQueryOptions.java b/hibernate-core/src/main/java/org/hibernate/query/spi/MutableQueryOptions.java index c8527845aee8..3087326425c9 100644 --- a/hibernate-core/src/main/java/org/hibernate/query/spi/MutableQueryOptions.java +++ b/hibernate-core/src/main/java/org/hibernate/query/spi/MutableQueryOptions.java @@ -11,10 +11,11 @@ import org.hibernate.FlushMode; import org.hibernate.graph.GraphSemantic; import org.hibernate.graph.spi.RootGraphImplementor; -import org.hibernate.query.QueryLogging; import org.hibernate.query.ResultListTransformer; import org.hibernate.query.TupleTransformer; +import static org.hibernate.query.QueryLogging.QUERY_LOGGER; + /** * @author Steve Ebersole */ @@ -39,7 +40,7 @@ public interface MutableQueryOptions extends QueryOptions { */ default void setCacheMode(CacheMode cacheMode) { if ( cacheMode == null ) { - QueryLogging.QUERY_LOGGER.debug( "Null CacheMode passed to #setCacheMode; falling back to `NORMAL`" ); + QUERY_LOGGER.debug( "Null CacheMode passed to #setCacheMode; falling back to 'NORMAL'" ); cacheMode = CacheMode.NORMAL; } diff --git a/hibernate-core/src/main/java/org/hibernate/query/sqm/function/SqmFunctionRegistry.java b/hibernate-core/src/main/java/org/hibernate/query/sqm/function/SqmFunctionRegistry.java index 6004eaf9e029..5620a0dbcaad 100644 --- a/hibernate-core/src/main/java/org/hibernate/query/sqm/function/SqmFunctionRegistry.java +++ b/hibernate-core/src/main/java/org/hibernate/query/sqm/function/SqmFunctionRegistry.java @@ -52,8 +52,6 @@ public Set getValidFunctionKeys() { /** * Useful for diagnostics - not efficient: do not use in production code. - * - * @return */ public Stream> getFunctionsByName() { final Map sortedFunctionMap = new TreeMap<>( CASE_INSENSITIVE_ORDER ); @@ -68,8 +66,6 @@ public Stream> getFunctionsByName() { /** * Useful for diagnostics - not efficient: do not use in production code. - * - * @return */ public Stream> getSetReturningFunctionsByName() { final Map sortedFunctionMap = new TreeMap<>( CASE_INSENSITIVE_ORDER ); @@ -125,7 +121,7 @@ public Stream> getSetReturn */ public SqmFunctionDescriptor register(String registrationKey, SqmFunctionDescriptor function) { final SqmFunctionDescriptor priorRegistration = functionMap.put( registrationKey, function ); - log.debugf( + log.tracef( "Registered SqmFunctionTemplate [%s] under %s; prior registration was %s", function, registrationKey, @@ -136,11 +132,11 @@ public SqmFunctionDescriptor register(String registrationKey, SqmFunctionDescrip } /** - * Register a set returning function descriptor by name + * Register a set-returning function descriptor by name */ public SqmSetReturningFunctionDescriptor register(String registrationKey, SqmSetReturningFunctionDescriptor function) { final SqmSetReturningFunctionDescriptor priorRegistration = setReturningFunctionMap.put( registrationKey, function ); - log.debugf( + log.tracef( "Registered SqmSetReturningFunctionTemplate [%s] under %s; prior registration was %s", function, registrationKey, @@ -389,7 +385,7 @@ public SqmFunctionDescriptor wrapInJdbcEscape(String name, SqmFunctionDescriptor public void registerAlternateKey(String alternateKey, String mappedKey) { assert functionMap.containsKey( mappedKey ); - log.debugf( "Registering alternate key : %s -> %s", alternateKey, mappedKey ); + log.tracef( "Registering alternate key : %s -> %s", alternateKey, mappedKey ); alternateKeyMap.put( alternateKey, mappedKey ); } @@ -575,8 +571,8 @@ private MultipatternSqmFunctionDescriptor registerPatterns( * incoming registry, potentially overriding its registrations */ public void overlay(SqmFunctionRegistry registryToOverly) { - // NOTE : done in this "direction" as it is easier to access the - // functionMap directly in performing this operation + // NOTE: done in this "direction" as it is easier to access the + // functionMap directly in performing this operation functionMap.forEach( registryToOverly::register ); alternateKeyMap.forEach( registryToOverly::registerAlternateKey ); } diff --git a/hibernate-core/src/main/java/org/hibernate/query/sqm/internal/SqmCriteriaNodeBuilder.java b/hibernate-core/src/main/java/org/hibernate/query/sqm/internal/SqmCriteriaNodeBuilder.java index 4c898dcc802a..0f10e58f3213 100644 --- a/hibernate-core/src/main/java/org/hibernate/query/sqm/internal/SqmCriteriaNodeBuilder.java +++ b/hibernate-core/src/main/java/org/hibernate/query/sqm/internal/SqmCriteriaNodeBuilder.java @@ -3030,7 +3030,7 @@ private Object readResolve() throws InvalidObjectException { private static SessionFactory locateSessionFactoryOnDeserialization(String uuid, String name) throws InvalidObjectException{ final SessionFactory uuidResult = SessionFactoryRegistry.INSTANCE.getSessionFactory( uuid ); if ( uuidResult != null ) { - LOG.debugf( "Resolved SessionFactory by UUID [%s]", uuid ); + LOG.tracef( "Resolved SessionFactory by UUID [%s]", uuid ); return uuidResult; } @@ -3039,7 +3039,7 @@ private static SessionFactory locateSessionFactoryOnDeserialization(String uuid, if ( name != null ) { final SessionFactory namedResult = SessionFactoryRegistry.INSTANCE.getNamedSessionFactory( name ); if ( namedResult != null ) { - LOG.debugf( "Resolved SessionFactory by name [%s]", name ); + LOG.tracef( "Resolved SessionFactory by name [%s]", name ); return namedResult; } } diff --git a/hibernate-core/src/main/java/org/hibernate/query/sqm/internal/SqmTreePrinter.java b/hibernate-core/src/main/java/org/hibernate/query/sqm/internal/SqmTreePrinter.java index 7de7fbf212c0..41b6f501f7bb 100644 --- a/hibernate-core/src/main/java/org/hibernate/query/sqm/internal/SqmTreePrinter.java +++ b/hibernate-core/src/main/java/org/hibernate/query/sqm/internal/SqmTreePrinter.java @@ -127,7 +127,7 @@ /** * Printer for an SQM tree - for debugging purpose * - * @implNote At the top-level (statement) we check against {@link #DEBUG_ENABLED} + * @implNote At the top-level (statement) we check against {@link #TRACE_ENABLED} * and decide whether to continue or not. That's to avoid unnecessary, continued * checking of that boolean. The assumption being that we only ever enter from * these statement rules @@ -138,10 +138,10 @@ public class SqmTreePrinter implements SemanticQueryWalker { private static final Logger log = Logger.getLogger( SqmTreePrinter.class ); private static final Logger LOGGER = QueryLogging.subLogger( "sqm.ast" ); - private static final boolean DEBUG_ENABLED = LOGGER.isDebugEnabled(); + private static final boolean TRACE_ENABLED = LOGGER.isTraceEnabled(); public static void logTree(SqmQuerySpec sqmQuerySpec, String header) { - if ( ! DEBUG_ENABLED ) { + if ( !TRACE_ENABLED ) { return; } @@ -151,11 +151,11 @@ public static void logTree(SqmQuerySpec sqmQuerySpec, String header) { final String title = header != null ? header : "SqmQuerySpec Tree"; - LOGGER.debugf( "%s :%n%s", title, treePrinter.buffer.toString() ); + LOGGER.tracef( "%s :%n%s", title, treePrinter.buffer.toString() ); } public static void logTree(SqmStatement sqmStatement) { - if ( ! DEBUG_ENABLED ) { + if ( !TRACE_ENABLED ) { return; } @@ -174,7 +174,7 @@ else if ( sqmStatement instanceof SqmInsertSelectStatement statement ) { printer.visitInsertSelectStatement( statement ); } - LOGGER.debugf( "SqmStatement Tree :%n%s", printer.buffer.toString() ); + LOGGER.tracef( "SqmStatement Tree :%n%s", printer.buffer.toString() ); } private final StringBuffer buffer = new StringBuffer(); @@ -294,7 +294,7 @@ private void logIndented(String pattern, Object... args) { @Override public Object visitDeleteStatement(SqmDeleteStatement statement) { - if ( DEBUG_ENABLED ) { + if ( TRACE_ENABLED ) { processStanza( "delete", () -> { @@ -309,7 +309,7 @@ public Object visitDeleteStatement(SqmDeleteStatement statement) { @Override public Object visitInsertSelectStatement(SqmInsertSelectStatement statement) { - if ( DEBUG_ENABLED ) { + if ( TRACE_ENABLED ) { processStanza( "insert", () -> { @@ -328,7 +328,7 @@ public Object visitInsertSelectStatement(SqmInsertSelectStatement statement) @Override public Object visitInsertValuesStatement(SqmInsertValuesStatement statement) { - if ( DEBUG_ENABLED ) { + if ( TRACE_ENABLED ) { processStanza( "insert", () -> { @@ -375,7 +375,7 @@ public Object visitConflictClause(SqmConflictClause sqmConflictClause) { @Override public Object visitSelectStatement(SqmSelectStatement statement) { - if ( DEBUG_ENABLED ) { + if ( TRACE_ENABLED ) { processStanza( "select", () -> statement.getQueryPart().accept( this ) @@ -387,7 +387,7 @@ public Object visitSelectStatement(SqmSelectStatement statement) { @Override public Object visitCteStatement(SqmCteStatement sqmCteStatement) { - if ( DEBUG_ENABLED ) { + if ( TRACE_ENABLED ) { logIndented( "cte" ); } @@ -401,7 +401,7 @@ public Object visitCteContainer(SqmCteContainer consumer) { @Override public Object visitUpdateStatement(SqmUpdateStatement statement) { - if ( DEBUG_ENABLED ) { + if ( TRACE_ENABLED ) { processStanza( statement.isVersioned() ? "update versioned" : "update", () -> { diff --git a/hibernate-core/src/main/java/org/hibernate/query/sqm/mutation/internal/temptable/GlobalTemporaryTableStrategy.java b/hibernate-core/src/main/java/org/hibernate/query/sqm/mutation/internal/temptable/GlobalTemporaryTableStrategy.java index ad4003588c38..b57321fbc367 100644 --- a/hibernate-core/src/main/java/org/hibernate/query/sqm/mutation/internal/temptable/GlobalTemporaryTableStrategy.java +++ b/hibernate-core/src/main/java/org/hibernate/query/sqm/mutation/internal/temptable/GlobalTemporaryTableStrategy.java @@ -65,7 +65,7 @@ public void prepare(MappingModelCreationProcess mappingModelCreationProcess, Jdb .requireService( ConfigurationService.class ); if ( configService.getSetting( CREATE_ID_TABLES, StandardConverters.BOOLEAN, true ) ) { - log.debugf( "Creating global-temp ID table: %s", getTemporaryTable().getTableExpression() ); + log.tracef( "Creating global-temp ID table: %s", getTemporaryTable().getTableExpression() ); final TemporaryTableHelper.TemporaryTableCreationWork temporaryTableCreationWork = new TemporaryTableHelper.TemporaryTableCreationWork( getTemporaryTable(), sessionFactory ); @@ -104,7 +104,7 @@ public void release(SessionFactoryImplementor sessionFactory, JdbcConnectionAcce dropIdTables = false; - log.debugf( "Dropping global-temp ID table : %s", getTemporaryTable().getTableExpression() ); + log.tracef( "Dropping global-temp ID table: %s", getTemporaryTable().getTableExpression() ); final TemporaryTableHelper.TemporaryTableDropWork temporaryTableDropWork = new TemporaryTableHelper.TemporaryTableDropWork( getTemporaryTable(), sessionFactory ); diff --git a/hibernate-core/src/main/java/org/hibernate/query/sqm/mutation/internal/temptable/PersistentTableStrategy.java b/hibernate-core/src/main/java/org/hibernate/query/sqm/mutation/internal/temptable/PersistentTableStrategy.java index 8349b900849e..a68fa387fe7c 100644 --- a/hibernate-core/src/main/java/org/hibernate/query/sqm/mutation/internal/temptable/PersistentTableStrategy.java +++ b/hibernate-core/src/main/java/org/hibernate/query/sqm/mutation/internal/temptable/PersistentTableStrategy.java @@ -131,12 +131,10 @@ public void release( dropIdTables = false; final TemporaryTable temporaryTable = getTemporaryTable(); - log.debugf( "Dropping persistent ID table : %s", temporaryTable.getTableExpression() ); + log.tracef( "Dropping persistent ID table: %s", temporaryTable.getTableExpression() ); - final TemporaryTableHelper.TemporaryTableDropWork temporaryTableDropWork = new TemporaryTableHelper.TemporaryTableDropWork( - temporaryTable, - sessionFactory - ); + final TemporaryTableHelper.TemporaryTableDropWork temporaryTableDropWork = + new TemporaryTableHelper.TemporaryTableDropWork( temporaryTable, sessionFactory ); Connection connection; try { connection = connectionAccess.obtainConnection(); diff --git a/hibernate-core/src/main/java/org/hibernate/query/sqm/mutation/internal/temptable/RestrictedDeleteExecutionDelegate.java b/hibernate-core/src/main/java/org/hibernate/query/sqm/mutation/internal/temptable/RestrictedDeleteExecutionDelegate.java index 924334b4928b..fafe02327b44 100644 --- a/hibernate-core/src/main/java/org/hibernate/query/sqm/mutation/internal/temptable/RestrictedDeleteExecutionDelegate.java +++ b/hibernate-core/src/main/java/org/hibernate/query/sqm/mutation/internal/temptable/RestrictedDeleteExecutionDelegate.java @@ -389,7 +389,7 @@ private int deleteFromNonRootTableWithoutIdTable( jdbcParameterBindings, executionContext ); - MUTATION_QUERY_LOGGER.debugf( "deleteFromNonRootTable - `%s` : %s rows", targetTableReference, rows ); + MUTATION_QUERY_LOGGER.tracef( "deleteFromNonRootTable - `%s` : %s rows", targetTableReference, rows ); return rows; } diff --git a/hibernate-core/src/main/java/org/hibernate/query/sqm/sql/BaseSqmToSqlAstConverter.java b/hibernate-core/src/main/java/org/hibernate/query/sqm/sql/BaseSqmToSqlAstConverter.java index 403523c804fa..ed393988418a 100644 --- a/hibernate-core/src/main/java/org/hibernate/query/sqm/sql/BaseSqmToSqlAstConverter.java +++ b/hibernate-core/src/main/java/org/hibernate/query/sqm/sql/BaseSqmToSqlAstConverter.java @@ -58,7 +58,6 @@ import org.hibernate.persister.entity.EntityNameUse; import org.hibernate.persister.entity.EntityPersister; import org.hibernate.type.BindableType; -import org.hibernate.query.QueryLogging; import org.hibernate.query.SemanticException; import org.hibernate.query.SortDirection; import org.hibernate.query.common.FetchClauseType; @@ -329,6 +328,7 @@ import static org.hibernate.boot.model.process.internal.InferredBasicValueResolver.resolveSqlTypeIndicators; import static org.hibernate.generator.EventType.INSERT; import static org.hibernate.internal.util.NullnessHelper.coalesceSuppliedValues; +import static org.hibernate.query.QueryLogging.QUERY_MESSAGE_LOGGER; import static org.hibernate.query.common.TemporalUnit.EPOCH; import static org.hibernate.query.common.TemporalUnit.NANOSECOND; import static org.hibernate.query.common.TemporalUnit.NATIVE; @@ -3290,7 +3290,7 @@ private TableGroup consumeAttributeJoin( // add any additional join restrictions if ( sqmJoin.getJoinPredicate() != null ) { if ( sqmJoin.isFetched() ) { - QueryLogging.QUERY_MESSAGE_LOGGER.debugf( "Join fetch [%s] is restricted", sqmJoinNavigablePath ); + QUERY_MESSAGE_LOGGER.debugf( "Join fetch [%s] is restricted", sqmJoinNavigablePath ); } final SqmJoin oldJoin = currentlyProcessingJoin; @@ -5807,7 +5807,7 @@ private MappingModelExpressible determineValueMapping(SqmExpression sqmExp } if ( sqmExpression instanceof SqmPath ) { - log.debugf( "Determining mapping-model type for SqmPath : %s ", sqmExpression ); + log.tracef( "Determining mapping-model type for SqmPath: %s ", sqmExpression ); final MappingModelExpressible mappingModelExpressible = resolveMappingModelExpressible( sqmExpression, domainModel, fromClauseIndex::findTableGroup ); if ( mappingModelExpressible != null ) { @@ -5880,7 +5880,7 @@ private MappingModelExpressible determineValueMapping(SqmExpression sqmExp } } - log.debugf( "Determining mapping-model type for generalized SqmExpression : %s", sqmExpression ); + log.tracef( "Determining mapping-model type for generalized SqmExpression: %s", sqmExpression ); final SqmExpressible nodeType = sqmExpression.getNodeType(); if ( nodeType == null ) { // We can't determine the type of the expression @@ -5935,7 +5935,7 @@ else if ( !( inferredMapping instanceof JavaObjectType ) ) { } protected MappingModelExpressible determineValueMapping(SqmParameter sqmParameter) { - log.debugf( "Determining mapping-model type for SqmParameter : %s", sqmParameter ); + log.tracef( "Determining mapping-model type for SqmParameter: %s", sqmParameter ); final QueryParameterImplementor queryParameter = domainParameterXref.getQueryParameter( sqmParameter ); final QueryParameterBinding binding = domainParameterBindings.getBinding( queryParameter ); final boolean bindingTypeExplicit = binding.getExplicitTemporalPrecision() != null; diff --git a/hibernate-core/src/main/java/org/hibernate/query/sqm/sql/FromClauseIndex.java b/hibernate-core/src/main/java/org/hibernate/query/sqm/sql/FromClauseIndex.java index ee37f07e87ef..a5efb15f44cb 100644 --- a/hibernate-core/src/main/java/org/hibernate/query/sqm/sql/FromClauseIndex.java +++ b/hibernate-core/src/main/java/org/hibernate/query/sqm/sql/FromClauseIndex.java @@ -53,7 +53,7 @@ public void register(SqmPath sqmPath, TableGroup tableGroup, NavigablePath id final TableGroup previousAliasReg = tableGroupByAliasXref.put( sqmPath.getExplicitAlias(), tableGroup ); if ( previousAliasReg != null && log.isDebugEnabled() ) { log.debugf( - "Encountered previous TableGroup registration [%s] for alias : %s", + "Encountered previous TableGroup registration [%s] for alias: %s", previousAliasReg, sqmPath.getExplicitAlias() ); diff --git a/hibernate-core/src/main/java/org/hibernate/query/sqm/tree/expression/AbstractSqmExpression.java b/hibernate-core/src/main/java/org/hibernate/query/sqm/tree/expression/AbstractSqmExpression.java index 37fa5f69fb88..068b5b6e93bc 100644 --- a/hibernate-core/src/main/java/org/hibernate/query/sqm/tree/expression/AbstractSqmExpression.java +++ b/hibernate-core/src/main/java/org/hibernate/query/sqm/tree/expression/AbstractSqmExpression.java @@ -41,8 +41,8 @@ public void applyInferableType(@Nullable SqmBindableType type) { } protected void internalApplyInferableType(@Nullable SqmBindableType newType) { - SqmTreeCreationLogger.LOGGER.debugf( - "Applying inferable type to SqmExpression [%s] : %s -> %s", + SqmTreeCreationLogger.LOGGER.tracef( + "Applying inferable type to SqmExpression [%s]: %s -> %s", this, getExpressible(), newType diff --git a/hibernate-core/src/main/java/org/hibernate/resource/jdbc/internal/AbstractLogicalConnectionImplementor.java b/hibernate-core/src/main/java/org/hibernate/resource/jdbc/internal/AbstractLogicalConnectionImplementor.java index 3d592a7b78ab..13ae57114afe 100644 --- a/hibernate-core/src/main/java/org/hibernate/resource/jdbc/internal/AbstractLogicalConnectionImplementor.java +++ b/hibernate-core/src/main/java/org/hibernate/resource/jdbc/internal/AbstractLogicalConnectionImplementor.java @@ -115,9 +115,7 @@ protected void resetConnection(boolean initiallyAutoCommit) { } } catch ( Exception e ) { - log.debug( - "Could not re-enable auto-commit on JDBC Connection after completion of JDBC-based transaction : " + e - ); + log.debug( "Could not re-enable auto-commit on JDBC Connection after completion of JDBC-based transaction", e ); } } diff --git a/hibernate-core/src/main/java/org/hibernate/resource/jdbc/internal/LogicalConnectionManagedImpl.java b/hibernate-core/src/main/java/org/hibernate/resource/jdbc/internal/LogicalConnectionManagedImpl.java index 0ef4cfd056e4..7bfcf0c40cc0 100644 --- a/hibernate-core/src/main/java/org/hibernate/resource/jdbc/internal/LogicalConnectionManagedImpl.java +++ b/hibernate-core/src/main/java/org/hibernate/resource/jdbc/internal/LogicalConnectionManagedImpl.java @@ -133,10 +133,10 @@ public void afterStatement() { super.afterStatement(); if ( connectionHandlingMode.getReleaseMode() == AFTER_STATEMENT ) { if ( getResourceRegistry().hasRegisteredResources() ) { - log.debug( "Skipping aggressive release of JDBC Connection after-statement due to held resources" ); + log.trace( "Skipping aggressive release of JDBC Connection after-statement due to held resources" ); } else { - log.debug( "Initiating JDBC connection release from afterStatement" ); + log.trace( "Initiating JDBC connection release from afterStatement" ); releaseConnectionIfNeeded(); } } @@ -146,7 +146,7 @@ public void afterStatement() { public void beforeTransactionCompletion() { super.beforeTransactionCompletion(); if ( connectionHandlingMode.getReleaseMode() == BEFORE_TRANSACTION_COMPLETION ) { - log.debug( "Initiating JDBC connection release from beforeTransactionCompletion" ); + log.trace( "Initiating JDBC connection release from beforeTransactionCompletion" ); releaseConnectionIfNeeded(); } } @@ -159,7 +159,7 @@ public void afterTransaction() { // - AFTER_STATEMENT cases that were circumvented due to held resources // - BEFORE_TRANSACTION_COMPLETION cases that were circumvented because a rollback occurred // (we don't get a beforeTransactionCompletion event on rollback). - log.debug( "Initiating JDBC connection release from afterTransaction" ); + log.trace( "Initiating JDBC connection release from afterTransaction" ); releaseConnectionIfNeeded(); } } diff --git a/hibernate-core/src/main/java/org/hibernate/resource/jdbc/internal/LogicalConnectionProvidedImpl.java b/hibernate-core/src/main/java/org/hibernate/resource/jdbc/internal/LogicalConnectionProvidedImpl.java index cbd8e8bec581..1c13afbdca8a 100644 --- a/hibernate-core/src/main/java/org/hibernate/resource/jdbc/internal/LogicalConnectionProvidedImpl.java +++ b/hibernate-core/src/main/java/org/hibernate/resource/jdbc/internal/LogicalConnectionProvidedImpl.java @@ -110,15 +110,15 @@ public void manualReconnect(Connection connection) { } else if ( connection == providedConnection ) { // likely an unmatched reconnect call (no matching disconnect call) - log.debug( "reconnecting the same connection that is already connected; should this connection have been disconnected?" ); + log.trace( "Reconnecting the same connection that is already connected; should this connection have been disconnected?" ); } else if ( providedConnection != null ) { throw new IllegalArgumentException( - "cannot reconnect to a new user-supplied connection because currently connected; must disconnect before reconnecting." + "Cannot reconnect to a new user-supplied connection because currently connected; must disconnect before reconnecting." ); } providedConnection = connection; - log.debug( "Manually reconnected logical connection" ); + log.trace( "Manually reconnected logical connection" ); } @Override diff --git a/hibernate-core/src/main/java/org/hibernate/resource/jdbc/internal/ResultsetsTrackingContainer.java b/hibernate-core/src/main/java/org/hibernate/resource/jdbc/internal/ResultsetsTrackingContainer.java index a705e362db9e..eb6696f85e7f 100644 --- a/hibernate-core/src/main/java/org/hibernate/resource/jdbc/internal/ResultsetsTrackingContainer.java +++ b/hibernate-core/src/main/java/org/hibernate/resource/jdbc/internal/ResultsetsTrackingContainer.java @@ -180,7 +180,7 @@ private boolean warnOnNotNull(ResultSetsSet existingEntry) { // Keep this at DEBUG level, rather than warn. Numerous connection pool implementations can return a // proxy/wrapper around the JDBC Statement, causing excessive logging here. See HHH-8210. if ( existingEntry == null ) { - log.debug( "ResultSet statement was not registered (on register)" ); + log.trace( "ResultSet statement was not registered (on register)" ); } return true; } diff --git a/hibernate-core/src/main/java/org/hibernate/resource/jdbc/spi/JdbcEventHandler.java b/hibernate-core/src/main/java/org/hibernate/resource/jdbc/spi/JdbcEventHandler.java index 4db1b7336258..7638ea5738aa 100644 --- a/hibernate-core/src/main/java/org/hibernate/resource/jdbc/spi/JdbcEventHandler.java +++ b/hibernate-core/src/main/java/org/hibernate/resource/jdbc/spi/JdbcEventHandler.java @@ -124,7 +124,7 @@ public void jdbcReleaseRegistryResourcesStart() { if ( jdbcCoordinatorSupplier != null ) { final JdbcCoordinator jdbcCoordinator = jdbcCoordinatorSupplier.get(); if ( jdbcCoordinator != null ) { - log.debug( "Aborting batches as part of ResourceRegistryStandardImpl#releaseResources" ); + log.trace( "Aborting batches as part of ResourceRegistryStandardImpl#releaseResources" ); jdbcCoordinator.abortBatch(); } } diff --git a/hibernate-core/src/main/java/org/hibernate/resource/transaction/backend/jdbc/internal/DdlTransactionIsolatorNonJtaImpl.java b/hibernate-core/src/main/java/org/hibernate/resource/transaction/backend/jdbc/internal/DdlTransactionIsolatorNonJtaImpl.java index a0f93e0b474e..58e51eedb88e 100644 --- a/hibernate-core/src/main/java/org/hibernate/resource/transaction/backend/jdbc/internal/DdlTransactionIsolatorNonJtaImpl.java +++ b/hibernate-core/src/main/java/org/hibernate/resource/transaction/backend/jdbc/internal/DdlTransactionIsolatorNonJtaImpl.java @@ -47,7 +47,7 @@ public Connection getIsolatedConnection(boolean autocommit) { if ( jdbcConnection.getAutoCommit() != autocommit ) { try { if ( autocommit ) { - ConnectionAccessLogger.INSTANCE.informConnectionLocalTransactionForNonJtaDdl( jdbcContext.getJdbcConnectionAccess() ); + ConnectionAccessLogger.INSTANCE.informConnectionLocalTransactionForNonJtaDdl(); jdbcConnection.commit(); } jdbcConnection.setAutoCommit( autocommit ); diff --git a/hibernate-core/src/main/java/org/hibernate/resource/transaction/backend/jdbc/internal/JdbcResourceLocalTransactionCoordinatorImpl.java b/hibernate-core/src/main/java/org/hibernate/resource/transaction/backend/jdbc/internal/JdbcResourceLocalTransactionCoordinatorImpl.java index 12d71928f901..ea32816be518 100644 --- a/hibernate-core/src/main/java/org/hibernate/resource/transaction/backend/jdbc/internal/JdbcResourceLocalTransactionCoordinatorImpl.java +++ b/hibernate-core/src/main/java/org/hibernate/resource/transaction/backend/jdbc/internal/JdbcResourceLocalTransactionCoordinatorImpl.java @@ -269,7 +269,7 @@ private void commitNoRollbackOnly() { } private void commitRollbackOnly() { - log.debug( "On commit, transaction was marked for rollback only, rolling back" ); + log.trace( "On commit, transaction was marked for rollback only, rolling back" ); rollback(); if ( jpaCompliance.isJpaTransactionComplianceEnabled() ) { throw new RollbackException( "Transaction was marked for rollback only" ); @@ -300,8 +300,8 @@ public TransactionStatus getStatus() { @Override public void markRollbackOnly() { if ( getStatus() != TransactionStatus.ROLLED_BACK ) { - if ( log.isDebugEnabled() ) { - log.debug( "JDBC transaction marked for rollback only (exception provided for stack trace)", + if ( log.isTraceEnabled() ) { + log.trace( "JDBC transaction marked for rollback only (exception provided for stack trace)", new Exception( "exception just for purpose of providing stack trace" ) ); } rollbackOnly = true; diff --git a/hibernate-core/src/main/java/org/hibernate/resource/transaction/backend/jta/internal/JtaIsolationDelegate.java b/hibernate-core/src/main/java/org/hibernate/resource/transaction/backend/jta/internal/JtaIsolationDelegate.java index 17fa1bb1a566..055aa7828839 100644 --- a/hibernate-core/src/main/java/org/hibernate/resource/transaction/backend/jta/internal/JtaIsolationDelegate.java +++ b/hibernate-core/src/main/java/org/hibernate/resource/transaction/backend/jta/internal/JtaIsolationDelegate.java @@ -115,7 +115,7 @@ private T doInSuspendedTransaction(HibernateCallable callable) { // First we suspend any current JTA transaction final Transaction surroundingTransaction = transactionManager.suspend(); if ( surroundingTransaction != null ) { - LOG.debugf( "Surrounding JTA transaction suspended [%s]", surroundingTransaction ); + LOG.tracef( "Surrounding JTA transaction suspended [%s]", surroundingTransaction ); } try { @@ -128,7 +128,7 @@ private T doInSuspendedTransaction(HibernateCallable callable) { try { if ( surroundingTransaction != null ) { transactionManager.resume( surroundingTransaction ); - LOG.debugf( "Surrounding JTA transaction resumed [%s]", surroundingTransaction ); + LOG.tracef( "Surrounding JTA transaction resumed [%s]", surroundingTransaction ); } } catch ( Throwable t2 ) { diff --git a/hibernate-core/src/main/java/org/hibernate/resource/transaction/backend/jta/internal/JtaTransactionCoordinatorImpl.java b/hibernate-core/src/main/java/org/hibernate/resource/transaction/backend/jta/internal/JtaTransactionCoordinatorImpl.java index f9b7454194b1..bdde96eebca4 100644 --- a/hibernate-core/src/main/java/org/hibernate/resource/transaction/backend/jta/internal/JtaTransactionCoordinatorImpl.java +++ b/hibernate-core/src/main/java/org/hibernate/resource/transaction/backend/jta/internal/JtaTransactionCoordinatorImpl.java @@ -157,7 +157,7 @@ private void joinJtaTransaction() { new RegisteredSynchronization( getSynchronizationCallbackCoordinator() ) ); getSynchronizationCallbackCoordinator().synchronizationRegistered(); synchronizationRegistered = true; - log.debug( "Hibernate RegisteredSynchronization successfully registered with JTA platform" ); + log.trace( "Hibernate RegisteredSynchronization successfully registered with JTA platform" ); // report entering into a "transactional context" getTransactionCoordinatorOwner().startTransactionBoundary(); } @@ -166,7 +166,7 @@ private void joinJtaTransaction() { @Override public void explicitJoin() { if ( synchronizationRegistered ) { - log.debug( "JTA transaction was already joined (RegisteredSynchronization already registered)" ); + log.trace( "JTA transaction was already joined (RegisteredSynchronization already registered)" ); } else { if ( getTransactionDriverControl().getStatus() != ACTIVE ) { diff --git a/hibernate-core/src/main/java/org/hibernate/resource/transaction/internal/SynchronizationRegistryStandardImpl.java b/hibernate-core/src/main/java/org/hibernate/resource/transaction/internal/SynchronizationRegistryStandardImpl.java index a7d266650c36..12ff3edfcf5f 100644 --- a/hibernate-core/src/main/java/org/hibernate/resource/transaction/internal/SynchronizationRegistryStandardImpl.java +++ b/hibernate-core/src/main/java/org/hibernate/resource/transaction/internal/SynchronizationRegistryStandardImpl.java @@ -98,8 +98,7 @@ public void notifySynchronizationsAfterTransactionCompletion(int status) { @Override public void clearSynchronizations() { - log.debug( "Clearing local Synchronizations" ); - + log.trace( "Clearing local Synchronizations" ); if ( synchronizations != null ) { synchronizations.clear(); } diff --git a/hibernate-core/src/main/java/org/hibernate/result/internal/OutputsImpl.java b/hibernate-core/src/main/java/org/hibernate/result/internal/OutputsImpl.java index 4a46a3999bc8..702fc81494fe 100644 --- a/hibernate-core/src/main/java/org/hibernate/result/internal/OutputsImpl.java +++ b/hibernate-core/src/main/java/org/hibernate/result/internal/OutputsImpl.java @@ -284,8 +284,8 @@ public Output getOutput() { } protected Output buildOutput() { - if ( log.isDebugEnabled() ) { - log.debugf( + if ( log.isTraceEnabled() ) { + log.tracef( "Building Return [isResultSet=%s, updateCount=%s, extendedReturn=%s]", isResultSet(), getUpdateCount(), diff --git a/hibernate-core/src/main/java/org/hibernate/service/internal/AbstractServiceRegistryImpl.java b/hibernate-core/src/main/java/org/hibernate/service/internal/AbstractServiceRegistryImpl.java index fb165e6a7b22..a3f0a80264ac 100644 --- a/hibernate-core/src/main/java/org/hibernate/service/internal/AbstractServiceRegistryImpl.java +++ b/hibernate-core/src/main/java/org/hibernate/service/internal/AbstractServiceRegistryImpl.java @@ -407,17 +407,11 @@ public synchronized void deRegisterChild(ServiceRegistryImplementor child) { childRegistries.remove( child ); if ( childRegistries.isEmpty() ) { if ( autoCloseRegistry ) { - log.debug( - "Implicitly destroying ServiceRegistry on de-registration " + - "of all child ServiceRegistries" - ); + log.trace( "Implicitly destroying ServiceRegistry on deregistration of all child ServiceRegistries" ); destroy(); } else { - log.debug( - "Skipping implicitly destroying ServiceRegistry on de-registration " + - "of all child ServiceRegistries" - ); + log.trace( "Skipping implicitly destroying ServiceRegistry on deregistration of all child ServiceRegistries" ); } } } diff --git a/hibernate-core/src/main/java/org/hibernate/service/internal/SessionFactoryServiceRegistryImpl.java b/hibernate-core/src/main/java/org/hibernate/service/internal/SessionFactoryServiceRegistryImpl.java index 43d7eaf453ed..8164ed2bd762 100644 --- a/hibernate-core/src/main/java/org/hibernate/service/internal/SessionFactoryServiceRegistryImpl.java +++ b/hibernate-core/src/main/java/org/hibernate/service/internal/SessionFactoryServiceRegistryImpl.java @@ -101,8 +101,8 @@ public ServiceRegistryImplementor getServiceRegistry() { public @Nullable R getService(Class serviceRole) { if ( serviceRole.equals( EventListenerRegistry.class ) ) { log.debug( - "EventListenerRegistry access via ServiceRegistry is deprecated. " + - "Use `sessionFactory.getEventEngine().getListenerRegistry()` instead" + "EventListenerRegistry access via ServiceRegistry is deprecated. " + + "Use 'sessionFactory.getEventEngine().getListenerRegistry()' instead" ); //noinspection unchecked diff --git a/hibernate-core/src/main/java/org/hibernate/sql/ast/SqlTreePrinter.java b/hibernate-core/src/main/java/org/hibernate/sql/ast/SqlTreePrinter.java index 359ddc3964d2..3a06e0ca7dd6 100644 --- a/hibernate-core/src/main/java/org/hibernate/sql/ast/SqlTreePrinter.java +++ b/hibernate-core/src/main/java/org/hibernate/sql/ast/SqlTreePrinter.java @@ -33,14 +33,11 @@ */ public class SqlTreePrinter { public static void logSqlAst(Statement sqlAstStatement) { - if ( ! SqlAstTreeLogger.INSTANCE.isDebugEnabled() ) { - return; + if ( SqlAstTreeLogger.INSTANCE.isTraceEnabled() ) { + final SqlTreePrinter printer = new SqlTreePrinter(); + printer.visitStatement( sqlAstStatement ); + SqlAstTreeLogger.INSTANCE.tracef( "SQL AST Tree:%n%s", printer.buffer ); } - - final SqlTreePrinter printer = new SqlTreePrinter(); - printer.visitStatement( sqlAstStatement ); - - SqlAstTreeLogger.INSTANCE.debugf( "SQL AST Tree:%n%s", printer.buffer ); } private final StringBuffer buffer = new StringBuffer(); @@ -229,7 +226,7 @@ private void logNode(String text, Runnable subTreeHandler, boolean indentContinu subTreeHandler.run(); } catch (Exception e) { - SqlAstTreeLogger.INSTANCE.debugf( e, "Error processing node {%s}", text ); + SqlAstTreeLogger.INSTANCE.tracef( e, "Error processing node {%s}", text ); } finally { if ( indentContinuation ) { diff --git a/hibernate-core/src/main/java/org/hibernate/sql/ast/spi/SimpleFromClauseAccessImpl.java b/hibernate-core/src/main/java/org/hibernate/sql/ast/spi/SimpleFromClauseAccessImpl.java index 88cc0a980103..669a1022ec74 100644 --- a/hibernate-core/src/main/java/org/hibernate/sql/ast/spi/SimpleFromClauseAccessImpl.java +++ b/hibernate-core/src/main/java/org/hibernate/sql/ast/spi/SimpleFromClauseAccessImpl.java @@ -116,9 +116,9 @@ private TableGroup getCorrelatedTableGroup(TableGroup tableGroup) { @Override public void registerTableGroup(NavigablePath navigablePath, TableGroup tableGroup) { final Logger logger = SqlTreeCreationLogger.LOGGER; - final boolean debugEnabled = logger.isDebugEnabled(); - if ( debugEnabled ) { - logger.debugf( + final boolean traceEnabled = logger.isTraceEnabled(); + if ( traceEnabled ) { + logger.tracef( "Registration of TableGroup [%s] with identifierForTableGroup [%s] for NavigablePath [%s] ", tableGroup, tableGroup.getNavigablePath().getIdentifierForTableGroup(), @@ -126,9 +126,9 @@ public void registerTableGroup(NavigablePath navigablePath, TableGroup tableGrou ); } final TableGroup previous = tableGroupMap.put( navigablePath, tableGroup ); - if ( debugEnabled && previous != null ) { - logger.debugf( - "Registration of TableGroup [%s] for NavigablePath [%s] overrode previous registration : %s", + if ( traceEnabled && previous != null ) { + logger.tracef( + "Registration of TableGroup [%s] for NavigablePath [%s] overrode previous registration: %s", tableGroup, navigablePath, previous diff --git a/hibernate-core/src/main/java/org/hibernate/sql/ast/spi/SqlAliasBaseImpl.java b/hibernate-core/src/main/java/org/hibernate/sql/ast/spi/SqlAliasBaseImpl.java index 2af3c78cf45c..6f4e93afd567 100644 --- a/hibernate-core/src/main/java/org/hibernate/sql/ast/spi/SqlAliasBaseImpl.java +++ b/hibernate-core/src/main/java/org/hibernate/sql/ast/spi/SqlAliasBaseImpl.java @@ -27,7 +27,7 @@ public String getAliasStem() { @Override public String generateNewAlias() { final String alias = stem + "_" + ( aliasCount++ ); - SqlTreeCreationLogger.LOGGER.debugf( "Created new SQL alias : %s", alias ); + SqlTreeCreationLogger.LOGGER.tracef( "Created new SQL alias: %s", alias ); return alias; } diff --git a/hibernate-core/src/main/java/org/hibernate/sql/ast/tree/expression/SqlTuple.java b/hibernate-core/src/main/java/org/hibernate/sql/ast/tree/expression/SqlTuple.java index 9a1c31f602a0..99fbf8b1d46d 100644 --- a/hibernate-core/src/main/java/org/hibernate/sql/ast/tree/expression/SqlTuple.java +++ b/hibernate-core/src/main/java/org/hibernate/sql/ast/tree/expression/SqlTuple.java @@ -12,7 +12,6 @@ import org.hibernate.query.sqm.SqmExpressible; import org.hibernate.query.sqm.sql.internal.DomainResultProducer; import org.hibernate.sql.ast.SqlAstWalker; -import org.hibernate.sql.ast.SqlTreeCreationLogger; import org.hibernate.sql.ast.spi.SqlAstCreationState; import org.hibernate.sql.ast.spi.SqlSelection; import org.hibernate.sql.ast.tree.update.Assignable; @@ -30,16 +29,6 @@ public class SqlTuple implements Expression, SqlTupleContainer, DomainResultProd public SqlTuple(List expressions, MappingModelExpressible valueMapping) { this.expressions = expressions; this.valueMapping = valueMapping; - - if ( SqlTreeCreationLogger.LOGGER.isDebugEnabled() ) { - final int size = expressions.size(); - if ( size < 2 ) { - SqlTreeCreationLogger.LOGGER.debugf( - "SqlTuple created with `%s` expression(s)", - size - ); - } - } } @Override diff --git a/hibernate-core/src/main/java/org/hibernate/sql/ast/tree/from/TableGroupJoin.java b/hibernate-core/src/main/java/org/hibernate/sql/ast/tree/from/TableGroupJoin.java index 2105763ff8db..8275e92e28b3 100644 --- a/hibernate-core/src/main/java/org/hibernate/sql/ast/tree/from/TableGroupJoin.java +++ b/hibernate-core/src/main/java/org/hibernate/sql/ast/tree/from/TableGroupJoin.java @@ -54,7 +54,7 @@ public SqlAstJoinType getJoinType() { } public void setJoinType(SqlAstJoinType joinType) { - SqlTreeCreationLogger.LOGGER.debugf( + SqlTreeCreationLogger.LOGGER.tracef( "Adjusting join-type for TableGroupJoin(%s) : %s -> %s", navigablePath, this.joinType, diff --git a/hibernate-core/src/main/java/org/hibernate/sql/exec/internal/JdbcSelectExecutorStandardImpl.java b/hibernate-core/src/main/java/org/hibernate/sql/exec/internal/JdbcSelectExecutorStandardImpl.java index a2e84cb2e28a..f4b79cfecb4a 100644 --- a/hibernate-core/src/main/java/org/hibernate/sql/exec/internal/JdbcSelectExecutorStandardImpl.java +++ b/hibernate-core/src/main/java/org/hibernate/sql/exec/internal/JdbcSelectExecutorStandardImpl.java @@ -18,7 +18,6 @@ import org.hibernate.engine.spi.SharedSessionContractImplementor; import org.hibernate.query.TupleTransformer; import org.hibernate.query.spi.QueryOptions; -import org.hibernate.sql.exec.SqlExecLogger; import org.hibernate.sql.exec.spi.ExecutionContext; import org.hibernate.sql.exec.spi.JdbcOperationQuerySelect; import org.hibernate.sql.exec.spi.JdbcParameterBindings; @@ -50,6 +49,7 @@ import static org.hibernate.internal.util.NullnessHelper.coalesceSuppliedValues; import static org.hibernate.internal.util.collections.ArrayHelper.indexOf; +import static org.hibernate.sql.exec.SqlExecLogger.SQL_EXEC_LOGGER; /** * Standard JdbcSelectExecutor implementation used by Hibernate, @@ -273,13 +273,13 @@ private JdbcValues resolveJdbcValuesSource( final QueryKey queryResultsCacheKey; final List cachedResults; if ( cacheable && cacheMode.isGetEnabled() ) { - SqlExecLogger.SQL_EXEC_LOGGER.debugf( "Reading Query result cache data per CacheMode#isGetEnabled [%s]", cacheMode.name() ); + SQL_EXEC_LOGGER.tracef( "Reading Query result cache data per CacheMode#isGetEnabled [%s]", cacheMode.name() ); final Set querySpaces = jdbcSelect.getAffectedTableNames(); if ( querySpaces == null || querySpaces.isEmpty() ) { - SqlExecLogger.SQL_EXEC_LOGGER.tracef( "Unexpected querySpaces is empty" ); + SQL_EXEC_LOGGER.tracef( "Unexpected querySpaces is empty" ); } else { - SqlExecLogger.SQL_EXEC_LOGGER.tracef( "querySpaces is `%s`", querySpaces ); + SQL_EXEC_LOGGER.tracef( "querySpaces is `%s`", querySpaces ); } final QueryResultsCache queryCache = factory.getCache() @@ -319,7 +319,7 @@ private JdbcValues resolveJdbcValuesSource( } } else { - SqlExecLogger.SQL_EXEC_LOGGER.debugf( "Skipping reading Query result cache data: cache-enabled = %s, cache-mode = %s", + SQL_EXEC_LOGGER.tracef( "Skipping reading Query result cache data: cache-enabled = %s, cache-mode = %s", queryCacheEnabled, cacheMode.name() ); diff --git a/hibernate-core/src/main/java/org/hibernate/sql/model/jdbc/OptionalTableUpdateOperation.java b/hibernate-core/src/main/java/org/hibernate/sql/model/jdbc/OptionalTableUpdateOperation.java index 6dcf099caa6b..7f017213c141 100644 --- a/hibernate-core/src/main/java/org/hibernate/sql/model/jdbc/OptionalTableUpdateOperation.java +++ b/hibernate-core/src/main/java/org/hibernate/sql/model/jdbc/OptionalTableUpdateOperation.java @@ -148,8 +148,8 @@ public void performMutation( } if ( !wasUpdated ) { - MODEL_MUTATION_LOGGER.debugf( - "Upsert update altered no rows - inserting : %s", + MODEL_MUTATION_LOGGER.tracef( + "Upsert update altered no rows - inserting: %s", tableMapping.getTableName() ); try { diff --git a/hibernate-core/src/main/java/org/hibernate/sql/results/graph/DomainResultGraphPrinter.java b/hibernate-core/src/main/java/org/hibernate/sql/results/graph/DomainResultGraphPrinter.java index 777fc0073fca..5282c9d2814f 100644 --- a/hibernate-core/src/main/java/org/hibernate/sql/results/graph/DomainResultGraphPrinter.java +++ b/hibernate-core/src/main/java/org/hibernate/sql/results/graph/DomainResultGraphPrinter.java @@ -25,7 +25,7 @@ public class DomainResultGraphPrinter { @SubSystemLogging( name = Logging.LOGGER_NAME, - description = "Logging of `DomainResult` graphs" + description = "Logging of DomainResult graphs" ) @Internal interface Logging { @@ -34,16 +34,13 @@ interface Logging { } public static void logDomainResultGraph(List> domainResults) { - logDomainResultGraph( "DomainResult Graph", domainResults ); + logDomainResultGraph( "DomainResult graph", domainResults ); } public static void logDomainResultGraph(String header, List> domainResults) { - if ( !AST_LOGGER.isDebugEnabled() ) { - return; + if ( AST_LOGGER.isTraceEnabled() ) { + new DomainResultGraphPrinter( header ).visitDomainResults( domainResults ); } - - final DomainResultGraphPrinter graphPrinter = new DomainResultGraphPrinter( header ); - graphPrinter.visitDomainResults( domainResults ); } private final StringBuilder buffer; @@ -64,11 +61,7 @@ private void visitDomainResults(List> domainResults) { visitGraphNode( domainResult, lastInBranch ); } - AST_LOGGER.debug( buffer.toString() ); - - if ( AST_LOGGER.isTraceEnabled() ) { - AST_LOGGER.tracef( new Exception(), "Stack trace calling DomainResultGraphPrinter" ); - } + AST_LOGGER.trace( buffer.toString() ); } private void visitGraphNode(DomainResultGraphNode node, boolean lastInBranch) { @@ -98,10 +91,6 @@ private void visitGraphNode(DomainResultGraphNode node, boolean lastInBranch, St } } - private void visitKeyGraphNode(DomainResultGraphNode node, boolean lastInBranch) { - visitGraphNode( node, lastInBranch, "(key) " + node.getClass().getSimpleName() ); - } - private void visitFetches(FetchParent fetchParent) { fetchParentStack.push( fetchParent ); diff --git a/hibernate-core/src/main/java/org/hibernate/sql/results/graph/embeddable/internal/EmbeddableInitializerImpl.java b/hibernate-core/src/main/java/org/hibernate/sql/results/graph/embeddable/internal/EmbeddableInitializerImpl.java index fc512a63092f..7265a086636b 100644 --- a/hibernate-core/src/main/java/org/hibernate/sql/results/graph/embeddable/internal/EmbeddableInitializerImpl.java +++ b/hibernate-core/src/main/java/org/hibernate/sql/results/graph/embeddable/internal/EmbeddableInitializerImpl.java @@ -469,7 +469,7 @@ private void prepareCompositeInstance(EmbeddableInitializerData data) { data.setInstance( createCompositeInstance( data ) ); } - EMBEDDED_LOAD_LOGGER.debugf( "Created composite instance [%s]", navigablePath ); + EMBEDDED_LOAD_LOGGER.tracef( "Created composite instance [%s]", navigablePath ); } private void extractRowState(EmbeddableInitializerData data) { @@ -519,7 +519,7 @@ private Object createCompositeInstance(EmbeddableInitializerData data) { : data.concreteEmbeddableType.getInstantiator(); final Object instance = instantiator.instantiate( data ); data.setState( State.RESOLVED ); - EMBEDDED_LOAD_LOGGER.debugf( "Created composite instance [%s] : %s", navigablePath, instance ); + EMBEDDED_LOAD_LOGGER.tracef( "Created composite instance [%s]: %s", navigablePath, instance ); return instance; } diff --git a/hibernate-core/src/main/java/org/hibernate/sql/results/graph/tuple/TupleResultAssembler.java b/hibernate-core/src/main/java/org/hibernate/sql/results/graph/tuple/TupleResultAssembler.java index 48298ec9e9b4..83887d070bc8 100644 --- a/hibernate-core/src/main/java/org/hibernate/sql/results/graph/tuple/TupleResultAssembler.java +++ b/hibernate-core/src/main/java/org/hibernate/sql/results/graph/tuple/TupleResultAssembler.java @@ -44,9 +44,9 @@ public J assemble( RowProcessingState rowProcessingState) { final Object[] jdbcValues = extractRawValue( rowProcessingState ); - if ( ResultsLogger.RESULTS_MESSAGE_LOGGER.isDebugEnabled() ) { + if ( ResultsLogger.RESULTS_MESSAGE_LOGGER.isTraceEnabled() ) { for ( int i = 0; i < valuesArrayPositions.length; i++ ) { - ResultsLogger.RESULTS_MESSAGE_LOGGER.debugf( + ResultsLogger.RESULTS_MESSAGE_LOGGER.tracef( "Extracted JDBC value [%d] - [%s]", valuesArrayPositions[i], jdbcValues[i] diff --git a/hibernate-core/src/main/java/org/hibernate/sql/results/internal/NavigablePathMapToInitializer.java b/hibernate-core/src/main/java/org/hibernate/sql/results/internal/NavigablePathMapToInitializer.java index 0320c98b8820..6d0f4d975e48 100644 --- a/hibernate-core/src/main/java/org/hibernate/sql/results/internal/NavigablePathMapToInitializer.java +++ b/hibernate-core/src/main/java/org/hibernate/sql/results/internal/NavigablePathMapToInitializer.java @@ -5,7 +5,6 @@ package org.hibernate.sql.results.internal; import java.util.HashMap; -import java.util.Map; import java.util.Objects; import org.hibernate.spi.NavigablePath; @@ -48,32 +47,31 @@ public void put(final NavigablePath navigablePath, final Initializer initiali } public void logInitializers() { - ResultsLogger logger = ResultsLogger.RESULTS_MESSAGE_LOGGER; - if ( !logger.isDebugEnabled() ) { - return; - } - if ( map == null ) { - logger.debug( "Initializer list is empty" ); - } - else { - //Apparently we want to log this on multiple lines (existing code did this - not sure if that was by design): - //using a StringBuilder to avoid potentially interleaving the logs from different operations. - final StringBuilder sb = new StringBuilder( "Initializer list:\n" ); - for ( Map.Entry holderEntry : map.entrySet() ) { - final NavigablePath navigablePath = holderEntry.getKey(); - final Initializer initializer = holderEntry.getValue().initializer; - String formatted = String.format( - " %s -> %s@%s (%s)", - navigablePath, - initializer, - initializer.hashCode(), - initializer.getInitializedPart() - ); - sb.append( '\t' ); - sb.append( formatted ); - sb.append( '\n' ); + final ResultsLogger logger = ResultsLogger.RESULTS_MESSAGE_LOGGER; + if ( logger.isTraceEnabled() ) { + if ( map == null ) { + logger.trace( "Initializer list is empty" ); + } + else { + //Apparently we want to log this on multiple lines (existing code did this - not sure if that was by design): + //using a StringBuilder to avoid potentially interleaving the logs from different operations. + final StringBuilder sb = new StringBuilder( "Initializer list:\n" ); + for ( var holderEntry : map.entrySet() ) { + final NavigablePath navigablePath = holderEntry.getKey(); + final Initializer initializer = holderEntry.getValue().initializer; + final String formatted = String.format( + " %s -> %s@%s (%s)", + navigablePath, + initializer, + initializer.hashCode(), + initializer.getInitializedPart() + ); + sb.append( '\t' ); + sb.append( formatted ); + sb.append( '\n' ); + } + logger.trace( sb.toString() ); } - logger.debug( sb.toString() ); } } diff --git a/hibernate-core/src/main/java/org/hibernate/sql/results/internal/ResultsHelper.java b/hibernate-core/src/main/java/org/hibernate/sql/results/internal/ResultsHelper.java index c595ebc20fb3..49751c32af96 100644 --- a/hibernate-core/src/main/java/org/hibernate/sql/results/internal/ResultsHelper.java +++ b/hibernate-core/src/main/java/org/hibernate/sql/results/internal/ResultsHelper.java @@ -23,7 +23,6 @@ import org.hibernate.metamodel.mapping.PluralAttributeMapping; import org.hibernate.persister.collection.CollectionPersister; import org.hibernate.persister.entity.EntityPersister; -import org.hibernate.pretty.MessageHelper; import org.hibernate.sql.results.jdbc.spi.JdbcValues; import org.hibernate.sql.results.jdbc.spi.JdbcValuesMapping; import org.hibernate.sql.results.jdbc.spi.JdbcValuesMappingResolution; @@ -32,6 +31,8 @@ import org.hibernate.stat.spi.StatisticsImplementor; import org.hibernate.type.EntityType; +import static org.hibernate.pretty.MessageHelper.collectionInfoString; + /** * @author Steve Ebersole */ @@ -107,10 +108,10 @@ public static void finalizeCollectionLoading( addCollectionToCache( persistenceContext, collectionDescriptor, collectionInstance, key ); } - if ( LOG.isDebugEnabled() ) { - LOG.debugf( + if ( LOG.isTraceEnabled() ) { + LOG.tracef( "Collection fully initialized: %s", - MessageHelper.collectionInfoString( + collectionInfoString( collectionDescriptor, collectionInstance, key, @@ -139,8 +140,9 @@ private static void addCollectionToCache( final SharedSessionContractImplementor session = persistenceContext.getSession(); final SessionFactoryImplementor factory = session.getFactory(); - if ( LOG.isDebugEnabled() ) { - LOG.debugf( "Caching collection: %s", MessageHelper.collectionInfoString( collectionDescriptor, collectionInstance, key, session ) ); + if ( LOG.isTraceEnabled() ) { + LOG.trace( "Caching collection: " + + collectionInfoString( collectionDescriptor, collectionInstance, key, session ) ); } if ( session.getLoadQueryInfluencers().hasEnabledFilters() && collectionDescriptor.isAffectedByEnabledFilters( session ) ) { diff --git a/hibernate-core/src/main/java/org/hibernate/stat/internal/StatisticsInitiator.java b/hibernate-core/src/main/java/org/hibernate/stat/internal/StatisticsInitiator.java index 8b2f49ba6ea4..10b9a8caf04b 100644 --- a/hibernate-core/src/main/java/org/hibernate/stat/internal/StatisticsInitiator.java +++ b/hibernate-core/src/main/java/org/hibernate/stat/internal/StatisticsInitiator.java @@ -44,7 +44,7 @@ public StatisticsImplementor initiateService(SessionFactoryServiceInitiatorConte final StatisticsImplementor statistics = statisticsFactory.buildStatistics( context.getSessionFactory() ); final boolean enabled = context.getSessionFactoryOptions().isStatisticsEnabled(); statistics.setStatisticsEnabled( enabled ); - LOG.debugf( "Statistics initialized [enabled=%s]", enabled ); + LOG.tracef( "Statistics initialized [enabled=%s]", enabled ); return statistics; } diff --git a/hibernate-core/src/main/java/org/hibernate/tool/schema/internal/AbstractSchemaMigrator.java b/hibernate-core/src/main/java/org/hibernate/tool/schema/internal/AbstractSchemaMigrator.java index cb969ea10e89..7c45c02edc6a 100644 --- a/hibernate-core/src/main/java/org/hibernate/tool/schema/internal/AbstractSchemaMigrator.java +++ b/hibernate-core/src/main/java/org/hibernate/tool/schema/internal/AbstractSchemaMigrator.java @@ -122,7 +122,7 @@ public void doMigration( target.release(); } catch (Exception e) { - log.debugf( "Problem releasing GenerationTarget [%s] : %s", target, e.getMessage() ); + log.debugf( "Problem releasing GenerationTarget [%s]: %s", target, e.getMessage() ); } } } @@ -132,7 +132,7 @@ public void doMigration( databaseInformation.cleanup(); } catch (Exception e) { - log.debug( "Problem releasing DatabaseInformation : " + e.getMessage() ); + log.debug( "Problem releasing DatabaseInformation: " + e.getMessage() ); } } } diff --git a/hibernate-core/src/main/java/org/hibernate/tool/schema/internal/AbstractSchemaValidator.java b/hibernate-core/src/main/java/org/hibernate/tool/schema/internal/AbstractSchemaValidator.java index 832f7a382a6b..2064db962a86 100644 --- a/hibernate-core/src/main/java/org/hibernate/tool/schema/internal/AbstractSchemaValidator.java +++ b/hibernate-core/src/main/java/org/hibernate/tool/schema/internal/AbstractSchemaValidator.java @@ -79,7 +79,7 @@ public void doValidation( databaseInformation.cleanup(); } catch (Exception e) { - log.debug( "Problem releasing DatabaseInformation : " + e.getMessage() ); + log.debug( "Problem releasing DatabaseInformation: " + e.getMessage() ); } isolator.release(); diff --git a/hibernate-core/src/main/java/org/hibernate/tool/schema/internal/Helper.java b/hibernate-core/src/main/java/org/hibernate/tool/schema/internal/Helper.java index d6faf6362894..ce6ba9ff03ba 100644 --- a/hibernate-core/src/main/java/org/hibernate/tool/schema/internal/Helper.java +++ b/hibernate-core/src/main/java/org/hibernate/tool/schema/internal/Helper.java @@ -65,7 +65,7 @@ public static ScriptSourceInput interpretScriptSourceSetting( } else { final String scriptSourceSettingString = scriptSourceSetting.toString(); - log.debugf( "Attempting to resolve script source setting : %s", scriptSourceSettingString ); + log.tracef( "Attempting to resolve script source setting: %s", scriptSourceSettingString ); final String[] paths = splitAtCommas( scriptSourceSettingString ); if ( paths.length == 1 ) { @@ -111,7 +111,7 @@ else if ( scriptTargetSetting instanceof Writer writer ) { } else { final String scriptTargetSettingString = scriptTargetSetting.toString(); - log.debugf( "Attempting to resolve script source setting : %s", scriptTargetSettingString ); + log.tracef( "Attempting to resolve script source setting: %s", scriptTargetSettingString ); // setting could be either: // 1) string URL representation (i.e., "file://...") diff --git a/hibernate-core/src/main/java/org/hibernate/tool/schema/internal/SchemaCreatorImpl.java b/hibernate-core/src/main/java/org/hibernate/tool/schema/internal/SchemaCreatorImpl.java index 711196135ac5..b97a515cbab5 100644 --- a/hibernate-core/src/main/java/org/hibernate/tool/schema/internal/SchemaCreatorImpl.java +++ b/hibernate-core/src/main/java/org/hibernate/tool/schema/internal/SchemaCreatorImpl.java @@ -135,7 +135,7 @@ public void doCreation( target.release(); } catch (Exception e) { - log.debugf( "Problem releasing GenerationTarget [%s] : %s", target, e.getMessage() ); + log.debugf( "Problem releasing GenerationTarget [%s]: %s", target, e.getMessage() ); } } } diff --git a/hibernate-core/src/main/java/org/hibernate/tool/schema/internal/SchemaDropperImpl.java b/hibernate-core/src/main/java/org/hibernate/tool/schema/internal/SchemaDropperImpl.java index ff9300587d4c..b1ad71fd6ec2 100644 --- a/hibernate-core/src/main/java/org/hibernate/tool/schema/internal/SchemaDropperImpl.java +++ b/hibernate-core/src/main/java/org/hibernate/tool/schema/internal/SchemaDropperImpl.java @@ -160,7 +160,7 @@ public void doDrop( target.release(); } catch (Exception e) { - log.debugf( "Problem releasing GenerationTarget [%s] : %s", target, e.getMessage() ); + log.debugf( "Problem releasing GenerationTarget [%s]: %s", target, e.getMessage() ); } } } diff --git a/hibernate-core/src/main/java/org/hibernate/tool/schema/internal/exec/JdbcConnectionAccessConnectionProviderImpl.java b/hibernate-core/src/main/java/org/hibernate/tool/schema/internal/exec/JdbcConnectionAccessConnectionProviderImpl.java index aa974f9320d0..4231d1609aa3 100644 --- a/hibernate-core/src/main/java/org/hibernate/tool/schema/internal/exec/JdbcConnectionAccessConnectionProviderImpl.java +++ b/hibernate-core/src/main/java/org/hibernate/tool/schema/internal/exec/JdbcConnectionAccessConnectionProviderImpl.java @@ -59,7 +59,7 @@ public JdbcConnectionAccessConnectionProviderImpl(ConnectionProvider connectionP wasInitiallyAutoCommit = false; } - log.debugf( "wasInitiallyAutoCommit=%s", wasInitiallyAutoCommit ); + log.tracef( "wasInitiallyAutoCommit=%s", wasInitiallyAutoCommit ); this.wasInitiallyAutoCommit = wasInitiallyAutoCommit; } diff --git a/hibernate-core/src/main/java/org/hibernate/tool/schema/internal/exec/JdbcConnectionAccessProvidedConnectionImpl.java b/hibernate-core/src/main/java/org/hibernate/tool/schema/internal/exec/JdbcConnectionAccessProvidedConnectionImpl.java index 98968326ea97..5c243055594d 100644 --- a/hibernate-core/src/main/java/org/hibernate/tool/schema/internal/exec/JdbcConnectionAccessProvidedConnectionImpl.java +++ b/hibernate-core/src/main/java/org/hibernate/tool/schema/internal/exec/JdbcConnectionAccessProvidedConnectionImpl.java @@ -50,7 +50,7 @@ public JdbcConnectionAccessProvidedConnectionImpl(Connection jdbcConnection) { wasInitiallyAutoCommit = false; } - log.debugf( "wasInitiallyAutoCommit=%s", wasInitiallyAutoCommit ); + log.tracef( "wasInitiallyAutoCommit=%s", wasInitiallyAutoCommit ); this.wasInitiallyAutoCommit = wasInitiallyAutoCommit; } diff --git a/hibernate-core/src/main/java/org/hibernate/tool/schema/internal/exec/ScriptTargetOutputToFile.java b/hibernate-core/src/main/java/org/hibernate/tool/schema/internal/exec/ScriptTargetOutputToFile.java index c07aa6e7085c..96923ef9277d 100644 --- a/hibernate-core/src/main/java/org/hibernate/tool/schema/internal/exec/ScriptTargetOutputToFile.java +++ b/hibernate-core/src/main/java/org/hibernate/tool/schema/internal/exec/ScriptTargetOutputToFile.java @@ -89,7 +89,7 @@ static Writer toFileWriter(File file, String charsetName, boolean append) { try { if ( ! file.exists() ) { // best effort, since this is very likely not allowed in EE environments - log.debug( "Attempting to create non-existent script target file : " + file.getAbsolutePath() ); + log.debug( "Attempting to create non-existent script target file: " + file.getAbsolutePath() ); if ( file.getParentFile() != null ) { file.getParentFile().mkdirs(); } @@ -97,7 +97,7 @@ static Writer toFileWriter(File file, String charsetName, boolean append) { } } catch (Exception e) { - log.debug( "Exception calling File#createNewFile : " + e ); + log.debug( "Exception calling File#createNewFile: " + e ); } try { return charsetName != null ? diff --git a/hibernate-core/src/main/java/org/hibernate/tool/schema/internal/exec/ScriptTargetOutputToUrl.java b/hibernate-core/src/main/java/org/hibernate/tool/schema/internal/exec/ScriptTargetOutputToUrl.java index 71df25485ade..d28249e2b56c 100644 --- a/hibernate-core/src/main/java/org/hibernate/tool/schema/internal/exec/ScriptTargetOutputToUrl.java +++ b/hibernate-core/src/main/java/org/hibernate/tool/schema/internal/exec/ScriptTargetOutputToUrl.java @@ -80,7 +80,7 @@ public void release() { private static Writer toWriter( URL url, String charsetName, boolean append ) { - log.debug( "Attempting to resolve writer for URL : " + url ); + log.debug( "Attempting to resolve writer for URL: " + url ); // technically only "strings corresponding to file URLs" are supported, which I take to mean URLs whose // protocol is "file" try { diff --git a/hibernate-core/src/main/java/org/hibernate/type/BasicTypeRegistry.java b/hibernate-core/src/main/java/org/hibernate/type/BasicTypeRegistry.java index 24a8767ec37d..29a98212ff52 100644 --- a/hibernate-core/src/main/java/org/hibernate/type/BasicTypeRegistry.java +++ b/hibernate-core/src/main/java/org/hibernate/type/BasicTypeRegistry.java @@ -271,7 +271,7 @@ private void applyOrOverwriteEntry(BasicType type) { final JdbcType jdbcType = type.getJdbcType(); final BasicType existing = registryForJdbcType( jdbcType ).put( type.getMappedJavaType(), type ); if ( existing != null ) { - LOG.debugf( + LOG.tracef( "BasicTypeRegistry registration overwritten (%s + %s); previous =`%s`", jdbcType.getFriendlyName(), type.getJavaTypeDescriptor(), @@ -367,7 +367,7 @@ private void primeRegistryEntry(BasicType type) { final JdbcType jdbcType = type.getJdbcType(); final BasicType existing = registryForJdbcType( jdbcType ).get( type.getMappedJavaType() ); if ( existing != null ) { - LOG.debugf( + LOG.tracef( "Skipping registration of BasicType (%s + %s); still priming. existing = %s", jdbcType.getFriendlyName(), type.getJavaTypeDescriptor(), @@ -395,11 +395,11 @@ private void applyRegistrationKeys(BasicType type, String[] keys) { //Incidentally this might help with map lookup efficiency too. key = key.intern(); - LOG.debugf( "Adding type registration %s -> %s", key, type ); + LOG.tracef( "Adding type registration %s -> %s", key, type ); final Type old = typesByName.put( key, type ); if ( old != null && old != type ) { - LOG.debugf( + LOG.tracef( "Type registration key [%s] overrode previous entry : `%s`", key, old @@ -420,11 +420,11 @@ private void applyRegistrationKeys(BasicTypeReference type, String[] keys) { //Incidentally this might help with map lookup efficiency too. key = key.intern(); - LOG.debugf( "Adding type registration %s -> %s", key, type ); + LOG.tracef( "Adding type registration %s -> %s", key, type ); final BasicTypeReference old = typeReferencesByName.put( key, type ); if ( old != null && old != type ) { - LOG.debugf( + LOG.tracef( "Type registration key [%s] overrode previous entry : `%s`", key, old diff --git a/hibernate-core/src/main/java/org/hibernate/type/descriptor/jdbc/spi/JdbcTypeRegistry.java b/hibernate-core/src/main/java/org/hibernate/type/descriptor/jdbc/spi/JdbcTypeRegistry.java index 5f37ee377fd1..8894708f7d79 100644 --- a/hibernate-core/src/main/java/org/hibernate/type/descriptor/jdbc/spi/JdbcTypeRegistry.java +++ b/hibernate-core/src/main/java/org/hibernate/type/descriptor/jdbc/spi/JdbcTypeRegistry.java @@ -70,7 +70,7 @@ public TypeConfiguration getTypeConfiguration() { public void addDescriptor(JdbcType jdbcType) { final JdbcType previous = descriptorMap.put( jdbcType.getDefaultSqlTypeCode(), jdbcType ); if ( previous != null && previous != jdbcType ) { - log.debugf( "addDescriptor(%s) replaced previous registration(%s)", jdbcType, previous ); + log.tracef( "addDescriptor(%s) replaced previous registration(%s)", jdbcType, previous ); } } @@ -78,7 +78,7 @@ public void addDescriptor(JdbcType jdbcType) { public void addDescriptor(int typeCode, JdbcType jdbcType) { final JdbcType previous = descriptorMap.put( typeCode, jdbcType ); if ( previous != null && previous != jdbcType ) { - log.debugf( "addDescriptor(%d, %s) replaced previous registration(%s)", typeCode, jdbcType, previous ); + log.tracef( "addDescriptor(%d, %s) replaced previous registration(%s)", typeCode, jdbcType, previous ); } } diff --git a/hibernate-core/src/main/java/org/hibernate/type/descriptor/sql/spi/DdlTypeRegistry.java b/hibernate-core/src/main/java/org/hibernate/type/descriptor/sql/spi/DdlTypeRegistry.java index eb5c4648398c..888811f6d693 100644 --- a/hibernate-core/src/main/java/org/hibernate/type/descriptor/sql/spi/DdlTypeRegistry.java +++ b/hibernate-core/src/main/java/org/hibernate/type/descriptor/sql/spi/DdlTypeRegistry.java @@ -59,7 +59,7 @@ public void addDescriptor(int sqlTypeCode, DdlType ddlType) { for ( String rawTypeName : previous.getRawTypeNames() ) { sqlTypes.remove( rawTypeName ); } - log.debugf( "addDescriptor(%d, %s) replaced previous registration(%s)", sqlTypeCode, ddlType, previous ); + log.tracef( "addDescriptor(%d, %s) replaced previous registration(%s)", sqlTypeCode, ddlType, previous ); } addSqlType( ddlType, sqlTypeCode ); } diff --git a/hibernate-core/src/main/java/org/hibernate/type/spi/TypeConfiguration.java b/hibernate-core/src/main/java/org/hibernate/type/spi/TypeConfiguration.java index 8d0d363ebb6d..56681c4f79ce 100644 --- a/hibernate-core/src/main/java/org/hibernate/type/spi/TypeConfiguration.java +++ b/hibernate-core/src/main/java/org/hibernate/type/spi/TypeConfiguration.java @@ -194,7 +194,7 @@ public MetadataBuildingContext getMetadataBuildingContext() { * @param metadataBuildingContext a {@link MetadataBuildingContext} */ public void scope(MetadataBuildingContext metadataBuildingContext) { - log.debugf( "Scoping TypeConfiguration [%s] to MetadataBuildingContext [%s]", this, metadataBuildingContext ); + log.tracef( "Scoping TypeConfiguration [%s] to MetadataBuildingContext [%s]", this, metadataBuildingContext ); scope.setMetadataBuildingContext( metadataBuildingContext ); } @@ -206,7 +206,7 @@ public void scope(MetadataBuildingContext metadataBuildingContext) { * @param sessionFactory a {@link SessionFactory} that is in a very fragile state */ public void scope(SessionFactoryImplementor sessionFactory) { - log.debugf( "Scoping TypeConfiguration [%s] to SessionFactoryImplementor [%s]", this, sessionFactory ); + log.tracef( "Scoping TypeConfiguration [%s] to SessionFactoryImplementor [%s]", this, sessionFactory ); if ( scope.getMetadataBuildingContext() == null ) { throw new IllegalStateException( "MetadataBuildingContext not known" ); @@ -605,7 +605,7 @@ private static String getFactoryName(SessionFactoryImplementor factory) { } private void unsetSessionFactory(SessionFactory factory) { - log.debugf( "Un-scoping TypeConfiguration [%s] from SessionFactory [%s]", this, factory ); + log.tracef( "Un-scoping TypeConfiguration [%s] from SessionFactory [%s]", this, factory ); sessionFactory = null; } From 055b4fe214e4688dc72e296ef605f8b6e5afac6f Mon Sep 17 00:00:00 2001 From: Gavin King Date: Sun, 13 Jul 2025 02:01:29 +0200 Subject: [PATCH 02/32] improvements to TRACE-level logging --- .../boot/model/internal/AnnotatedColumn.java | 2 +- .../BootstrapServiceRegistryImpl.java | 4 +- .../spi/support/AbstractReadWriteAccess.java | 2 +- .../internal/NaturalIdResolutionsImpl.java | 6 +- .../internal/StatefulPersistenceContext.java | 12 ++-- .../engine/jdbc/batch/JdbcBatchLogging.java | 8 +++ .../engine/jdbc/batch/internal/BatchImpl.java | 2 +- .../jdbc/internal/JdbcCoordinatorImpl.java | 37 ++++++++-- .../internal/AbstractMutationExecutor.java | 2 +- .../AbstractPreparedStatementGroup.java | 2 +- .../hibernate/engine/spi/IdentifierValue.java | 2 +- .../hibernate/engine/spi/VersionValue.java | 2 +- .../transaction/internal/TransactionImpl.java | 6 +- .../graph/internal/parse/GraphParser.java | 4 +- .../hibernate/internal/CoreMessageLogger.java | 11 ++- .../internal/SessionFactoryImpl.java | 4 +- .../internal/SessionFactoryRegistry.java | 2 +- .../org/hibernate/mapping/BasicValue.java | 8 +-- .../mapping/MappingModelCreationLogging.java | 3 +- .../internal/MappingModelCreationHelper.java | 2 +- .../internal/MappingModelCreationProcess.java | 6 +- .../collection/BasicCollectionPersister.java | 49 +++++++------ .../collection/OneToManyPersister.java | 25 ++++--- .../AbstractUpdateRowsCoordinator.java | 2 +- .../DeleteRowsCoordinatorStandard.java | 2 +- ...DeleteRowsCoordinatorTablePerSubclass.java | 2 +- .../InsertRowsCoordinatorStandard.java | 2 +- ...InsertRowsCoordinatorTablePerSubclass.java | 2 +- .../mutation/RemoveCoordinatorStandard.java | 8 +-- .../RemoveCoordinatorTablePerSubclass.java | 8 +-- .../entity/AbstractEntityPersister.java | 43 +++++++----- .../entity/EntityPropertyMapping.java | 17 ++--- .../internal/BasicDotIdentifierConsumer.java | 1 - .../hql/internal/SemanticQueryBuilder.java | 2 +- .../hql/internal/SqmTreeCreationHelper.java | 5 +- .../QueryInterpretationCacheStandardImpl.java | 10 +-- .../function/NamedSqmFunctionDescriptor.java | 6 +- .../PatternBasedSqmFunctionDescriptor.java | 15 +++- .../sqm/internal/SqmInterpretationsKey.java | 5 ++ .../query/sqm/internal/SqmTreePrinter.java | 52 +++++++------- .../sqm/sql/BaseSqmToSqlAstConverter.java | 69 +++++++++---------- .../expression/AbstractSqmExpression.java | 13 ++-- .../AbstractLogicalConnectionImplementor.java | 7 +- .../LogicalConnectionManagedImpl.java | 8 +-- .../ResourceRegistryStandardImpl.java | 26 +++++-- .../resource/jdbc/spi/JdbcEventHandler.java | 1 - ...sourceLocalTransactionCoordinatorImpl.java | 7 +- .../JtaTransactionCoordinatorImpl.java | 23 ++++--- .../SynchronizationRegistryStandardImpl.java | 9 +-- .../internal/AbstractServiceRegistryImpl.java | 4 +- .../SessionFactoryServiceRegistryImpl.java | 4 +- .../org/hibernate/sql/ast/SqlTreePrinter.java | 53 +++++++------- .../ast/spi/SimpleFromClauseAccessImpl.java | 39 +++++------ .../sql/ast/spi/SqlAliasBaseImpl.java | 3 +- .../ast/tree/from/DerivedTableReference.java | 4 +- .../sql/ast/tree/from/TableGroupJoin.java | 13 ++-- .../JdbcSelectExecutorStandardImpl.java | 4 +- .../builder/AbstractTableMutationBuilder.java | 2 +- .../model/jdbc/DeleteOrUpsertOperation.java | 8 +-- .../jdbc/OptionalTableUpdateOperation.java | 4 +- .../internal/EmbeddableInitializerImpl.java | 8 +-- .../NavigablePathMapToInitializer.java | 55 +++++++-------- .../internal/StandardJdbcValuesMapping.java | 65 ++++++++--------- .../spi/SchemaManagementToolCoordinator.java | 4 +- .../hibernate/type/spi/TypeConfiguration.java | 18 ++--- .../transaction/TransactionTimeoutTests.java | 2 +- .../softdelete/CustomTrueFalseConverter.java | 2 +- .../testing/transaction/TransactionUtil2.java | 6 +- 68 files changed, 448 insertions(+), 396 deletions(-) diff --git a/hibernate-core/src/main/java/org/hibernate/boot/model/internal/AnnotatedColumn.java b/hibernate-core/src/main/java/org/hibernate/boot/model/internal/AnnotatedColumn.java index 270316510207..f0385ea2ab6f 100644 --- a/hibernate-core/src/main/java/org/hibernate/boot/model/internal/AnnotatedColumn.java +++ b/hibernate-core/src/main/java/org/hibernate/boot/model/internal/AnnotatedColumn.java @@ -274,7 +274,7 @@ public void bind() { if ( generatedAs != null ) { mappingColumn.setGeneratedAs( generatedAs ); } - if ( LOG.isDebugEnabled() ) { + if ( LOG.isDebugEnabled() && logicalColumnName != null ) { LOG.trace( "Binding column: " + logicalColumnName ); } } diff --git a/hibernate-core/src/main/java/org/hibernate/boot/registry/internal/BootstrapServiceRegistryImpl.java b/hibernate-core/src/main/java/org/hibernate/boot/registry/internal/BootstrapServiceRegistryImpl.java index e9e18dcdcd26..f470982bb3a4 100644 --- a/hibernate-core/src/main/java/org/hibernate/boot/registry/internal/BootstrapServiceRegistryImpl.java +++ b/hibernate-core/src/main/java/org/hibernate/boot/registry/internal/BootstrapServiceRegistryImpl.java @@ -292,11 +292,11 @@ public synchronized void deRegisterChild(ServiceRegistryImplementor child) { childRegistries.remove( child ); if ( childRegistries.isEmpty() ) { if ( autoCloseRegistry ) { - LOG.trace( "Implicitly destroying Bootstrap registry on deregistration of all child ServiceRegistries" ); + LOG.trace( "Automatically destroying bootstrap registry after deregistration of every child ServiceRegistry" ); destroy(); } else { - LOG.trace( "Skipping implicitly destroying Bootstrap registry on deregistration of all child ServiceRegistries" ); + LOG.trace( "Skipping destroying bootstrap registry after deregistration of every child ServiceRegistry" ); } } } diff --git a/hibernate-core/src/main/java/org/hibernate/cache/spi/support/AbstractReadWriteAccess.java b/hibernate-core/src/main/java/org/hibernate/cache/spi/support/AbstractReadWriteAccess.java index b729bb328e5f..bb30d0ed308d 100644 --- a/hibernate-core/src/main/java/org/hibernate/cache/spi/support/AbstractReadWriteAccess.java +++ b/hibernate-core/src/main/java/org/hibernate/cache/spi/support/AbstractReadWriteAccess.java @@ -106,7 +106,7 @@ public boolean putFromLoad( try { final boolean traceEnabled = log.isTraceEnabled(); if ( traceEnabled ) { - log.tracef( "Caching data from load [region=`%s` (%s)] : key[%s] -> value[%s]", getRegion().getName(), getAccessType(), key, value ); + log.tracef( "Caching data from load [region='%s' (%s)] : key[%s] -> value[%s]", getRegion().getName(), getAccessType(), key, value ); } writeLock.lock(); Lockable item = (Lockable) getStorageAccess().getFromCache( key, session ); diff --git a/hibernate-core/src/main/java/org/hibernate/engine/internal/NaturalIdResolutionsImpl.java b/hibernate-core/src/main/java/org/hibernate/engine/internal/NaturalIdResolutionsImpl.java index 98cd1ae333c4..e6fd5f1f564f 100644 --- a/hibernate-core/src/main/java/org/hibernate/engine/internal/NaturalIdResolutionsImpl.java +++ b/hibernate-core/src/main/java/org/hibernate/engine/internal/NaturalIdResolutionsImpl.java @@ -67,7 +67,7 @@ public boolean cacheResolution(Object id, Object naturalId, EntityMappingType en @Override public void cacheResolutionFromLoad(Object id, Object naturalId, EntityMappingType entityDescriptor) { NaturalIdLogging.NATURAL_ID_LOGGER.tracef( - "Caching resolution natural-id resolution from load (%s) : `%s` -> `%s`", + "Caching natural id resolution from load (%s) : '%s' -> '%s'", entityDescriptor.getEntityName(), naturalId, id @@ -101,7 +101,7 @@ private boolean cacheResolutionLocally(Object id, Object naturalId, EntityMappin assert isValidValue( naturalId, entityDescriptor ); NaturalIdLogging.NATURAL_ID_LOGGER.tracef( - "Locally caching natural-id resolution (%s) : `%s` -> `%s`", + "Locally caching natural id resolution (%s) : '%s' -> '%s'", entityDescriptor.getEntityName(), naturalId, id @@ -160,7 +160,7 @@ public void manageLocalResolution( @Override public Object removeLocalResolution(Object id, Object naturalId, EntityMappingType entityDescriptor) { NaturalIdLogging.NATURAL_ID_LOGGER.tracef( - "Removing locally cached natural-id resolution (%s) : `%s` -> `%s`", + "Removing locally cached natural id resolution (%s) : '%s' -> '%s'", entityDescriptor.getEntityName(), naturalId, id diff --git a/hibernate-core/src/main/java/org/hibernate/engine/internal/StatefulPersistenceContext.java b/hibernate-core/src/main/java/org/hibernate/engine/internal/StatefulPersistenceContext.java index 668177d53299..89d64b029f0b 100644 --- a/hibernate-core/src/main/java/org/hibernate/engine/internal/StatefulPersistenceContext.java +++ b/hibernate-core/src/main/java/org/hibernate/engine/internal/StatefulPersistenceContext.java @@ -1149,7 +1149,7 @@ public void initializeNonLazyCollections() throws HibernateException { @Override public void initializeNonLazyCollections(Consumer> initializeAction ) { if ( loadCounter == 0 ) { - LOG.trace( "Initializing non-lazy collections" ); +// LOG.trace( "Initializing non-lazy collections" ); // do this work only at the very highest level of the load // don't let this method be called recursively loadCounter++; @@ -1525,7 +1525,7 @@ && isFoundInParent( propertyName, childEntity, persister, collectionPersister, p unmergedInstance ); LOG.tracef( - "Detached object being merged (corresponding with a managed entity) has a collection that [%s] the detached child.", + "Detached object being merged (corresponding with a managed entity) has a collection that [%s] the detached child", ( found ? "contains" : "does not contain" ) ); } @@ -1556,7 +1556,7 @@ && isFoundInParent( propertyName, childEntity, persister, collectionPersister, p mergeMap.get( proxy ) ); LOG.debugf( - "Detached proxy being merged has a collection that [%s] the managed child.", + "Detached proxy being merged has a collection that [%s] the managed child", (found ? "contains" : "does not contain") ); if ( !found ) { @@ -1568,7 +1568,7 @@ && isFoundInParent( propertyName, childEntity, persister, collectionPersister, p mergeMap.get( proxy ) ); LOG.debugf( - "Detached proxy being merged has a collection that [%s] the detached child being merged..", + "Detached proxy being merged has a collection that [%s] the detached child being merged", (found ? "contains" : "does not contain") ); } @@ -1820,7 +1820,7 @@ public void replaceEntityEntryRowId(Object entity, Object rowId) { * @throws IOException serialization errors. */ public void serialize(ObjectOutputStream oos) throws IOException { - LOG.trace( "Serializing persistence-context" ); + LOG.trace( "Serializing persistence context" ); oos.writeBoolean( defaultReadOnly ); oos.writeBoolean( hasNonReadOnlyEntities ); @@ -1925,7 +1925,7 @@ private void writeCollectionToStream( public static StatefulPersistenceContext deserialize( ObjectInputStream ois, SessionImplementor session) throws IOException, ClassNotFoundException { - LOG.trace( "Deserializing persistence-context" ); + LOG.trace( "Deserializing persistence context" ); final StatefulPersistenceContext rtn = new StatefulPersistenceContext( session ); SessionFactoryImplementor sfi = session.getFactory(); diff --git a/hibernate-core/src/main/java/org/hibernate/engine/jdbc/batch/JdbcBatchLogging.java b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/batch/JdbcBatchLogging.java index fa7c8b544da5..bf2d695fd069 100644 --- a/hibernate-core/src/main/java/org/hibernate/engine/jdbc/batch/JdbcBatchLogging.java +++ b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/batch/JdbcBatchLogging.java @@ -61,4 +61,12 @@ public interface JdbcBatchLogging extends BasicLogger { @LogMessage(level = TRACE) @Message("Executing JDBC batch (%s / %s) - [%s]") void executeBatch(int batchPosition, int batchSize, String string); + + @LogMessage(level = TRACE) + @Message("Conditionally executing JDBC batch - [%s]") + void conditionallyExecuteBatch(String string); + + @LogMessage(level = TRACE) + @Message("Aborting JDBC batch - [%s]") + void abortBatch(String string); } diff --git a/hibernate-core/src/main/java/org/hibernate/engine/jdbc/batch/internal/BatchImpl.java b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/batch/internal/BatchImpl.java index e675fb553fb0..8f3563512705 100644 --- a/hibernate-core/src/main/java/org/hibernate/engine/jdbc/batch/internal/BatchImpl.java +++ b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/batch/internal/BatchImpl.java @@ -123,7 +123,7 @@ public void addToBatch(JdbcValueBindings jdbcValueBindings, TableInclusionChecke && !inclusionChecker.include( statementDetails.getMutatingTableDetails() ) ) { if ( loggerTraceEnabled ) { MODEL_MUTATION_LOGGER.tracef( - "Skipping addBatch for table : %s (batch-position=%s)", + "Skipping addBatch for table: %s (batch position %s)", statementDetails.getMutatingTableDetails().getTableName(), batchPosition+1 ); diff --git a/hibernate-core/src/main/java/org/hibernate/engine/jdbc/internal/JdbcCoordinatorImpl.java b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/internal/JdbcCoordinatorImpl.java index 6241a214ed6b..9215626da507 100644 --- a/hibernate-core/src/main/java/org/hibernate/engine/jdbc/internal/JdbcCoordinatorImpl.java +++ b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/internal/JdbcCoordinatorImpl.java @@ -7,7 +7,6 @@ import org.hibernate.ConnectionReleaseMode; import org.hibernate.HibernateException; import org.hibernate.TransactionException; -import org.hibernate.engine.jdbc.batch.JdbcBatchLogging; import org.hibernate.engine.jdbc.batch.spi.Batch; import org.hibernate.engine.jdbc.batch.spi.BatchKey; import org.hibernate.engine.jdbc.mutation.group.PreparedStatementGroup; @@ -39,6 +38,7 @@ import java.util.function.Supplier; import static org.hibernate.ConnectionReleaseMode.AFTER_STATEMENT; +import static org.hibernate.engine.jdbc.batch.JdbcBatchLogging.BATCH_MESSAGE_LOGGER; /** * Standard implementation of {@link JdbcCoordinator}. @@ -81,6 +81,9 @@ public JdbcCoordinatorImpl( this.jdbcServices = jdbcServices; this.isUserSuppliedConnection = userSuppliedConnection != null; this.logicalConnection = createLogicalConnection( userSuppliedConnection, owner ); + if ( TRACE_ENABLED ) { + LOG.tracef( "Created JdbcCoordinator @%s", hashCode() ); + } } private static LogicalConnectionImplementor createLogicalConnection( @@ -101,6 +104,9 @@ private JdbcCoordinatorImpl( this.isUserSuppliedConnection = isUserSuppliedConnection; this.owner = owner; this.jdbcServices = owner.getJdbcSessionContext().getJdbcServices(); + if ( TRACE_ENABLED ) { + LOG.tracef( "Created JdbcCoordinator @%s", hashCode() ); + } } @Override @@ -142,7 +148,9 @@ public void flushEnding() { @Override public Connection close() { - if ( TRACE_ENABLED ) LOG.tracev( "Closing JDBC container [{0}]", this ); + if ( TRACE_ENABLED ) { + LOG.tracef( "Closing JdbcCoordinator @%s", hashCode() ); + } Connection connection; try { if ( currentBatch != null ) { @@ -193,7 +201,7 @@ public void executeBatch() { @Override public void conditionallyExecuteBatch(BatchKey key) { if ( currentBatch != null && !currentBatch.getKey().equals( key ) ) { - JdbcBatchLogging.BATCH_LOGGER.debugf( "Conditionally executing batch - %s", currentBatch.getKey() ); + BATCH_MESSAGE_LOGGER.conditionallyExecuteBatch( currentBatch.getKey().toLoggableString() ); try { currentBatch.execute(); } @@ -206,6 +214,7 @@ public void conditionallyExecuteBatch(BatchKey key) { @Override public void abortBatch() { if ( currentBatch != null ) { + BATCH_MESSAGE_LOGGER.abortBatch( currentBatch.getKey() .toLoggableString()); currentBatch.release(); } } @@ -257,7 +266,7 @@ public int determineRemainingTransactionTimeOutPeriod() { } final long millisecondsRemaining = transactionTimeOutInstant - System.currentTimeMillis(); if ( millisecondsRemaining <= 0L ) { - throw new TransactionException( "transaction timeout expired" ); + throw new TransactionException( "Transaction timeout expired" ); } return Math.max( (int) (millisecondsRemaining / 1000), 1 ); } @@ -266,7 +275,8 @@ public int determineRemainingTransactionTimeOutPeriod() { public void afterStatementExecution() { final ConnectionReleaseMode connectionReleaseMode = connectionReleaseMode(); if ( TRACE_ENABLED ) { - LOG.tracev( "Starting after statement execution processing [{0}]", connectionReleaseMode ); + LOG.tracef( "Statement execution complete (connection release mode %s) in JdbcCoordinator @%s", + connectionReleaseMode, hashCode() ); } if ( connectionReleaseMode == AFTER_STATEMENT ) { if ( ! releasesEnabled ) { @@ -309,7 +319,7 @@ public T coordinateWork(WorkExecutorVisitable work) { return result; } catch ( SQLException e ) { - throw sqlExceptionHelper().convert( e, "error executing work" ); + throw sqlExceptionHelper().convert( e, "Error executing work" ); } } @@ -323,7 +333,9 @@ public boolean isReadyForSerialization() { @Override @SuppressWarnings("unchecked") public void registerLastQuery(Statement statement) { - if ( TRACE_ENABLED ) LOG.tracev( "Registering last query statement [{0}]", statement ); +// if ( TRACE_ENABLED ) { +// LOG.tracef( "Registering last query statement [%s] @%s", statement, hashCode() ); +// } if ( statement instanceof JdbcWrapper ) { final JdbcWrapper wrapper = (JdbcWrapper) statement; registerLastQuery( wrapper.getWrappedObject() ); @@ -371,17 +383,28 @@ public boolean isActive() { @Override public void afterTransactionBegin() { + if ( TRACE_ENABLED ) { + LOG.tracef( "Transaction after begin in JdbcCoordinator @%s", hashCode() ); + } owner.afterTransactionBegin(); } @Override public void beforeTransactionCompletion() { + if ( TRACE_ENABLED ) { + LOG.tracef( "Transaction before completion in JdbcCoordinator @%s", hashCode() ); + } owner.beforeTransactionCompletion(); logicalConnection.beforeTransactionCompletion(); } @Override public void afterTransactionCompletion(boolean successful, boolean delayed) { + if ( TRACE_ENABLED ) { + LOG.tracef( "Transaction after %s completion in JdbcCoordinator @%s", + successful ? "successful" : "unsuccessful", + hashCode() ); + } afterTransaction(); owner.afterTransactionCompletion( successful, delayed ); } diff --git a/hibernate-core/src/main/java/org/hibernate/engine/jdbc/mutation/internal/AbstractMutationExecutor.java b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/mutation/internal/AbstractMutationExecutor.java index 006dbb0e11c1..384a8bd1a3e9 100644 --- a/hibernate-core/src/main/java/org/hibernate/engine/jdbc/mutation/internal/AbstractMutationExecutor.java +++ b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/mutation/internal/AbstractMutationExecutor.java @@ -116,7 +116,7 @@ protected void performNonBatchedMutation( if ( inclusionChecker != null && !inclusionChecker.include( tableDetails ) ) { if ( MODEL_MUTATION_LOGGER.isTraceEnabled() ) { MODEL_MUTATION_LOGGER.tracef( - "Skipping execution of secondary insert : %s", + "Skipping execution of secondary insert: %s", tableDetails.getTableName() ); } diff --git a/hibernate-core/src/main/java/org/hibernate/engine/jdbc/mutation/internal/AbstractPreparedStatementGroup.java b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/mutation/internal/AbstractPreparedStatementGroup.java index 0bce8fa5e044..e3e8d67123ec 100644 --- a/hibernate-core/src/main/java/org/hibernate/engine/jdbc/mutation/internal/AbstractPreparedStatementGroup.java +++ b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/mutation/internal/AbstractPreparedStatementGroup.java @@ -45,7 +45,7 @@ protected void release(PreparedStatementDetails statementDetails) { if ( statementDetails.toRelease() ) { if ( statementDetails.getStatement() == null ) { BATCH_LOGGER.debugf( - "PreparedStatementDetails did not contain PreparedStatement on #releaseStatements : %s", + "PreparedStatementDetails did not contain PreparedStatement on releaseStatements: %s", statementDetails.getSqlString() ); } diff --git a/hibernate-core/src/main/java/org/hibernate/engine/spi/IdentifierValue.java b/hibernate-core/src/main/java/org/hibernate/engine/spi/IdentifierValue.java index 189bfded5613..9a80e4c3c1b1 100644 --- a/hibernate-core/src/main/java/org/hibernate/engine/spi/IdentifierValue.java +++ b/hibernate-core/src/main/java/org/hibernate/engine/spi/IdentifierValue.java @@ -127,7 +127,7 @@ public IdentifierValue(Object value) { */ @Override public @Nullable Boolean isUnsaved(@Nullable Object id) { - LOG.tracev( "ID unsaved-value: {0}", value ); + LOG.tracef( "ID unsaved-value: %s", value ); return id == null || id.equals( value ); } diff --git a/hibernate-core/src/main/java/org/hibernate/engine/spi/VersionValue.java b/hibernate-core/src/main/java/org/hibernate/engine/spi/VersionValue.java index 09c494f3aa71..e8a71b6836b2 100644 --- a/hibernate-core/src/main/java/org/hibernate/engine/spi/VersionValue.java +++ b/hibernate-core/src/main/java/org/hibernate/engine/spi/VersionValue.java @@ -115,7 +115,7 @@ public VersionValue(Object value) { @Override public @Nullable Boolean isUnsaved(@Nullable Object version) throws MappingException { - LOG.tracev( "Version unsaved-value: {0}", value ); + LOG.tracef( "Version unsaved-value: %s", value ); return version == null || version.equals( value ); } diff --git a/hibernate-core/src/main/java/org/hibernate/engine/transaction/internal/TransactionImpl.java b/hibernate-core/src/main/java/org/hibernate/engine/transaction/internal/TransactionImpl.java index a496cce6d577..438d8b391b6b 100644 --- a/hibernate-core/src/main/java/org/hibernate/engine/transaction/internal/TransactionImpl.java +++ b/hibernate-core/src/main/java/org/hibernate/engine/transaction/internal/TransactionImpl.java @@ -72,7 +72,7 @@ else if ( !transactionCoordinator.getTransactionCoordinatorBuilder().isJta() ) { } } else { - LOG.debug( "begin transaction" ); + LOG.debug( "Beginning transaction" ); transactionDriverControl.begin(); } } @@ -85,7 +85,7 @@ public void commit() { throw new IllegalStateException( "Transaction not successfully started" ); } else { - LOG.debug( "committing transaction" ); + LOG.debug( "Committing transaction" ); try { internalGetTransactionDriverControl().commit(); } @@ -120,7 +120,7 @@ else if ( !status.canRollback() ) { throw new TransactionException( "Cannot roll back transaction in current status [" + status.name() + "]" ); } else if ( status != TransactionStatus.FAILED_COMMIT || allowFailedCommitToPhysicallyRollback() ) { - LOG.debug( "rolling back transaction" ); + LOG.debug( "Rolling back transaction" ); internalGetTransactionDriverControl().rollback(); } } diff --git a/hibernate-core/src/main/java/org/hibernate/graph/internal/parse/GraphParser.java b/hibernate-core/src/main/java/org/hibernate/graph/internal/parse/GraphParser.java index 8af0e761dee7..e02e5f06ee03 100644 --- a/hibernate-core/src/main/java/org/hibernate/graph/internal/parse/GraphParser.java +++ b/hibernate-core/src/main/java/org/hibernate/graph/internal/parse/GraphParser.java @@ -127,7 +127,7 @@ private PathQualifierType resolvePathQualifier(String qualifier) { return PathQualifierType.VALUE; } - throw new InvalidGraphException( "Invalid path qualifier [" + qualifier + "] - expecting `key` or `value`" ); + throw new InvalidGraphException( "Invalid path qualifier [" + qualifier + "] - expecting 'key' or 'value'" ); } @Override @@ -136,7 +136,7 @@ public SubGraphImplementor visitSubGraph(GraphLanguageParser.SubGraphContext if ( PARSING_LOGGER.isTraceEnabled() ) { PARSING_LOGGER.tracef( - "%s Starting graph : %s", + "%s Starting graph: %s", StringHelper.repeat( ">>", attributeNodeStack.depth() + 2 ), subTypeName ); diff --git a/hibernate-core/src/main/java/org/hibernate/internal/CoreMessageLogger.java b/hibernate-core/src/main/java/org/hibernate/internal/CoreMessageLogger.java index e4c891cec5c7..0fcdf01cf583 100644 --- a/hibernate-core/src/main/java/org/hibernate/internal/CoreMessageLogger.java +++ b/hibernate-core/src/main/java/org/hibernate/internal/CoreMessageLogger.java @@ -19,7 +19,6 @@ import org.hibernate.JDBCException; import org.hibernate.LockMode; import org.hibernate.cache.CacheException; -import org.hibernate.engine.spi.SessionFactoryImplementor; import org.hibernate.id.IntegralDataTypeHolder; import org.hibernate.service.Service; import org.hibernate.type.SerializationException; @@ -285,11 +284,11 @@ void missingArguments( @Message(value = "Running schema validator", id = 229) void runningSchemaValidator(); - @LogMessage(level = WARN) - @Message(value = "Scoping types to session factory %s after already scoped %s", id = 233) - void scopingTypesToSessionFactoryAfterAlreadyScoped( - SessionFactoryImplementor factory, - SessionFactoryImplementor factory2); +// @LogMessage(level = WARN) +// @Message(value = "Scoping types to session factory %s after already scoped %s", id = 233) +// void scopingTypesToSessionFactoryAfterAlreadyScoped( +// SessionFactoryImplementor factory, +// SessionFactoryImplementor factory2); // @LogMessage(level = WARN) // @Message(value = "SQL Error: %s, SQLState: %s", id = 247) diff --git a/hibernate-core/src/main/java/org/hibernate/internal/SessionFactoryImpl.java b/hibernate-core/src/main/java/org/hibernate/internal/SessionFactoryImpl.java index a3ef4a7a0b96..2d0fa0eb0ba8 100644 --- a/hibernate-core/src/main/java/org/hibernate/internal/SessionFactoryImpl.java +++ b/hibernate-core/src/main/java/org/hibernate/internal/SessionFactoryImpl.java @@ -361,7 +361,9 @@ public SessionFactoryImpl( throw e; } - LOG.trace( "Instantiated factory" ); + if ( LOG.isTraceEnabled() ) { + LOG.trace( "Instantiated factory: " + uuid ); + } } private EventMonitor loadEventMonitor() { diff --git a/hibernate-core/src/main/java/org/hibernate/internal/SessionFactoryRegistry.java b/hibernate-core/src/main/java/org/hibernate/internal/SessionFactoryRegistry.java index 8b5ece7f29f9..368955923885 100644 --- a/hibernate-core/src/main/java/org/hibernate/internal/SessionFactoryRegistry.java +++ b/hibernate-core/src/main/java/org/hibernate/internal/SessionFactoryRegistry.java @@ -48,7 +48,7 @@ public class SessionFactoryRegistry { private final ConcurrentHashMap nameUuidXref = new ConcurrentHashMap<>(); private SessionFactoryRegistry() { - LOG.tracef( "Initializing SessionFactoryRegistry: %s", this ); + LOG.tracef( "Initializing SessionFactoryRegistry @%s", hashCode() ); } /** diff --git a/hibernate-core/src/main/java/org/hibernate/mapping/BasicValue.java b/hibernate-core/src/main/java/org/hibernate/mapping/BasicValue.java index d3df1d8606e2..e9d3d9e0dce0 100644 --- a/hibernate-core/src/main/java/org/hibernate/mapping/BasicValue.java +++ b/hibernate-core/src/main/java/org/hibernate/mapping/BasicValue.java @@ -287,10 +287,10 @@ private void checkSelectable(Selectable incomingColumn) { throw new IllegalArgumentException( "Incoming column was null" ); } - final Selectable column = getColumn(); - if ( column == incomingColumn || column.getText().equals( incomingColumn.getText() ) ) { - log.debugf( "Skipping column re-registration: %s.%s", getTable().getName(), column.getText() ); - } +// final Selectable column = getColumn(); +// if ( column == incomingColumn || column.getText().equals( incomingColumn.getText() ) ) { +// log.debugf( "Skipping column re-registration: %s.%s", getTable().getName(), column.getText() ); +// } // else { // throw new IllegalStateException( // "BasicValue [" + ownerName + "." + propertyName + diff --git a/hibernate-core/src/main/java/org/hibernate/metamodel/mapping/MappingModelCreationLogging.java b/hibernate-core/src/main/java/org/hibernate/metamodel/mapping/MappingModelCreationLogging.java index 0b28fe620168..87863523a66c 100644 --- a/hibernate-core/src/main/java/org/hibernate/metamodel/mapping/MappingModelCreationLogging.java +++ b/hibernate-core/src/main/java/org/hibernate/metamodel/mapping/MappingModelCreationLogging.java @@ -30,5 +30,6 @@ public interface MappingModelCreationLogging extends BasicLogger { String LOGGER_NAME = SubSystemLogging.BASE + ".model.mapping.creation"; Logger MAPPING_MODEL_CREATION_LOGGER = Logger.getLogger( LOGGER_NAME ); - MappingModelCreationLogging MAPPING_MODEL_CREATION_MESSAGE_LOGGER = Logger.getMessageLogger( MethodHandles.lookup(), MappingModelCreationLogging.class, LOGGER_NAME ); + MappingModelCreationLogging MAPPING_MODEL_CREATION_MESSAGE_LOGGER = + Logger.getMessageLogger( MethodHandles.lookup(), MappingModelCreationLogging.class, LOGGER_NAME ); } diff --git a/hibernate-core/src/main/java/org/hibernate/metamodel/mapping/internal/MappingModelCreationHelper.java b/hibernate-core/src/main/java/org/hibernate/metamodel/mapping/internal/MappingModelCreationHelper.java index 40185ab12259..579e78181ab6 100644 --- a/hibernate-core/src/main/java/org/hibernate/metamodel/mapping/internal/MappingModelCreationHelper.java +++ b/hibernate-core/src/main/java/org/hibernate/metamodel/mapping/internal/MappingModelCreationHelper.java @@ -235,7 +235,7 @@ public static BasicAttributeMapping buildBasicAttributeMapping( if ( declaringType instanceof EmbeddableMappingType embeddableMappingType ) { if ( bootProperty.isLazy() ) { MAPPING_MODEL_CREATION_MESSAGE_LOGGER.debugf( - "Attribute was declared lazy, but is part of an embeddable - `%s#%s` - LAZY will be ignored", + "Attribute was declared LAZY, but is part of embeddable '%s#%s', LAZY ignored", declaringType.getNavigableRole().getFullPath(), bootProperty.getName() ); diff --git a/hibernate-core/src/main/java/org/hibernate/metamodel/mapping/internal/MappingModelCreationProcess.java b/hibernate-core/src/main/java/org/hibernate/metamodel/mapping/internal/MappingModelCreationProcess.java index 447e093129dd..df3cdd2148c7 100644 --- a/hibernate-core/src/main/java/org/hibernate/metamodel/mapping/internal/MappingModelCreationProcess.java +++ b/hibernate-core/src/main/java/org/hibernate/metamodel/mapping/internal/MappingModelCreationProcess.java @@ -99,7 +99,7 @@ private void execute() { } private void executePostInitCallbacks() { - MAPPING_MODEL_CREATION_MESSAGE_LOGGER.tracef( "Starting post-init callbacks" ); +// MAPPING_MODEL_CREATION_MESSAGE_LOGGER.tracef( "Starting post-init callbacks" ); Map exceptions = new HashMap<>(); while ( postInitCallbacks != null && !postInitCallbacks.isEmpty() ) { @@ -201,7 +201,7 @@ private void withForeignKey(NavigableRole navigableRole, Consumer> existingConsumers = keyDescriptorWaitingConsumerMap.get( navigableRole ); + final var existingConsumers = keyDescriptorWaitingConsumerMap.get( navigableRole ); final List> consumers; if ( existingConsumers != null ) { consumers = existingConsumers; @@ -218,7 +218,7 @@ public void registerForeignKey(ModelPart keyOwner, ForeignKeyDescriptor keyDescr final NavigableRole navigableRole = keyOwner.getNavigableRole(); keyDescriptorMap.put( navigableRole, keyDescriptor ); - final List> waitingConsumers = keyDescriptorWaitingConsumerMap.remove( navigableRole ); + final var waitingConsumers = keyDescriptorWaitingConsumerMap.remove( navigableRole ); if ( waitingConsumers != null ) { for ( int i = 0; i < waitingConsumers.size(); i++ ) { waitingConsumers.get( i ).accept( keyDescriptor ); diff --git a/hibernate-core/src/main/java/org/hibernate/persister/collection/BasicCollectionPersister.java b/hibernate-core/src/main/java/org/hibernate/persister/collection/BasicCollectionPersister.java index 9f4764119335..8f8a2a2ac690 100644 --- a/hibernate-core/src/main/java/org/hibernate/persister/collection/BasicCollectionPersister.java +++ b/hibernate-core/src/main/java/org/hibernate/persister/collection/BasicCollectionPersister.java @@ -58,7 +58,6 @@ import java.util.List; import static org.hibernate.internal.util.collections.CollectionHelper.arrayList; -import static org.hibernate.sql.model.ModelMutationLogging.MODEL_MUTATION_LOGGER; /** * A {@link CollectionPersister} for {@linkplain jakarta.persistence.ElementCollection @@ -144,12 +143,12 @@ private UpdateRowsCoordinator buildUpdateRowCoordinator() { && !isInverse(); if ( !performUpdates ) { - if ( MODEL_MUTATION_LOGGER.isTraceEnabled() ) { - MODEL_MUTATION_LOGGER.tracef( - "Skipping collection row updates - %s", - getRolePath() - ); - } +// if ( MODEL_MUTATION_LOGGER.isTraceEnabled() ) { +// MODEL_MUTATION_LOGGER.tracef( +// "Skipping collection row updates - %s", +// getRolePath() +// ); +// } return new UpdateRowsCoordinatorNoOp( this ); } @@ -158,12 +157,12 @@ private UpdateRowsCoordinator buildUpdateRowCoordinator() { private InsertRowsCoordinator buildInsertRowCoordinator() { if ( isInverse() || !isRowInsertEnabled() ) { - if ( MODEL_MUTATION_LOGGER.isTraceEnabled() ) { - MODEL_MUTATION_LOGGER.tracef( - "Skipping collection inserts - %s", - getRolePath() - ); - } +// if ( MODEL_MUTATION_LOGGER.isTraceEnabled() ) { +// MODEL_MUTATION_LOGGER.tracef( +// "Skipping collection inserts - %s", +// getRolePath() +// ); +// } return new InsertRowsCoordinatorNoOp( this ); } @@ -172,12 +171,12 @@ private InsertRowsCoordinator buildInsertRowCoordinator() { private DeleteRowsCoordinator buildDeleteRowCoordinator() { if ( ! needsRemove() ) { - if ( MODEL_MUTATION_LOGGER.isTraceEnabled() ) { - MODEL_MUTATION_LOGGER.tracef( - "Skipping collection row deletions - %s", - getRolePath() - ); - } +// if ( MODEL_MUTATION_LOGGER.isTraceEnabled() ) { +// MODEL_MUTATION_LOGGER.tracef( +// "Skipping collection row deletions - %s", +// getRolePath() +// ); +// } return new DeleteRowsCoordinatorNoOp( this ); } @@ -186,12 +185,12 @@ private DeleteRowsCoordinator buildDeleteRowCoordinator() { private RemoveCoordinator buildDeleteAllCoordinator() { if ( ! needsRemove() ) { - if ( MODEL_MUTATION_LOGGER.isTraceEnabled() ) { - MODEL_MUTATION_LOGGER.tracef( - "Skipping collection removals - %s", - getRolePath() - ); - } +// if ( MODEL_MUTATION_LOGGER.isTraceEnabled() ) { +// MODEL_MUTATION_LOGGER.tracef( +// "Skipping collection removals - %s", +// getRolePath() +// ); +// } return new RemoveCoordinatorNoOp( this ); } diff --git a/hibernate-core/src/main/java/org/hibernate/persister/collection/OneToManyPersister.java b/hibernate-core/src/main/java/org/hibernate/persister/collection/OneToManyPersister.java index b71cd203e6fd..87210cbb1c6c 100644 --- a/hibernate-core/src/main/java/org/hibernate/persister/collection/OneToManyPersister.java +++ b/hibernate-core/src/main/java/org/hibernate/persister/collection/OneToManyPersister.java @@ -76,7 +76,6 @@ import static org.hibernate.internal.util.NullnessHelper.areAllNonNull; import static org.hibernate.internal.util.collections.ArrayHelper.isAnyTrue; import static org.hibernate.internal.util.collections.CollectionHelper.arrayList; -import static org.hibernate.sql.model.ModelMutationLogging.MODEL_MUTATION_LOGGER; import static org.hibernate.sql.model.ast.builder.TableUpdateBuilder.NULL; /** @@ -407,9 +406,9 @@ private RowMutationOperations buildRowMutationOperations() { private InsertRowsCoordinator buildInsertCoordinator() { if ( isInverse() || !isRowInsertEnabled() ) { - if ( MODEL_MUTATION_LOGGER.isTraceEnabled() ) { - MODEL_MUTATION_LOGGER.tracef( "Skipping collection (re)creation - %s", getRolePath() ); - } +// if ( MODEL_MUTATION_LOGGER.isTraceEnabled() ) { +// MODEL_MUTATION_LOGGER.tracef( "Skipping collection (re)creation - %s", getRolePath() ); +// } return new InsertRowsCoordinatorNoOp( this ); } else { @@ -424,9 +423,9 @@ private InsertRowsCoordinator buildInsertCoordinator() { private UpdateRowsCoordinator buildUpdateCoordinator() { if ( !isRowDeleteEnabled() && !isRowInsertEnabled() ) { - if ( MODEL_MUTATION_LOGGER.isTraceEnabled() ) { - MODEL_MUTATION_LOGGER.tracef( "Skipping collection row updates - %s", getRolePath() ); - } +// if ( MODEL_MUTATION_LOGGER.isTraceEnabled() ) { +// MODEL_MUTATION_LOGGER.tracef( "Skipping collection row updates - %s", getRolePath() ); +// } return new UpdateRowsCoordinatorNoOp( this ); } else { @@ -440,9 +439,9 @@ private UpdateRowsCoordinator buildUpdateCoordinator() { private DeleteRowsCoordinator buildDeleteCoordinator() { if ( !needsRemove() ) { - if ( MODEL_MUTATION_LOGGER.isTraceEnabled() ) { - MODEL_MUTATION_LOGGER.tracef( "Skipping collection row deletions - %s", getRolePath() ); - } +// if ( MODEL_MUTATION_LOGGER.isTraceEnabled() ) { +// MODEL_MUTATION_LOGGER.tracef( "Skipping collection row deletions - %s", getRolePath() ); +// } return new DeleteRowsCoordinatorNoOp( this ); } else { @@ -458,9 +457,9 @@ private DeleteRowsCoordinator buildDeleteCoordinator() { private RemoveCoordinator buildDeleteAllCoordinator() { if ( ! needsRemove() ) { - if ( MODEL_MUTATION_LOGGER.isTraceEnabled() ) { - MODEL_MUTATION_LOGGER.tracef( "Skipping collection removals - %s", getRolePath() ); - } +// if ( MODEL_MUTATION_LOGGER.isTraceEnabled() ) { +// MODEL_MUTATION_LOGGER.tracef( "Skipping collection removals - %s", getRolePath() ); +// } return new RemoveCoordinatorNoOp( this ); } else { diff --git a/hibernate-core/src/main/java/org/hibernate/persister/collection/mutation/AbstractUpdateRowsCoordinator.java b/hibernate-core/src/main/java/org/hibernate/persister/collection/mutation/AbstractUpdateRowsCoordinator.java index 7413d03331c1..b3727a815d40 100644 --- a/hibernate-core/src/main/java/org/hibernate/persister/collection/mutation/AbstractUpdateRowsCoordinator.java +++ b/hibernate-core/src/main/java/org/hibernate/persister/collection/mutation/AbstractUpdateRowsCoordinator.java @@ -46,7 +46,7 @@ public void updateRows(Object key, PersistentCollection collection, SharedSes // update all the modified entries int count = doUpdate( key, collection, session ); - MODEL_MUTATION_LOGGER.tracef( "Updated `%s` collection rows - %s#%s", count, mutationTarget.getRolePath(), key ); + MODEL_MUTATION_LOGGER.tracef( "Updated %s collection rows - %s#%s", count, mutationTarget.getRolePath(), key ); } protected abstract int doUpdate(Object key, PersistentCollection collection, SharedSessionContractImplementor session); diff --git a/hibernate-core/src/main/java/org/hibernate/persister/collection/mutation/DeleteRowsCoordinatorStandard.java b/hibernate-core/src/main/java/org/hibernate/persister/collection/mutation/DeleteRowsCoordinatorStandard.java index 9e21a7df0897..37aed66af72a 100644 --- a/hibernate-core/src/main/java/org/hibernate/persister/collection/mutation/DeleteRowsCoordinatorStandard.java +++ b/hibernate-core/src/main/java/org/hibernate/persister/collection/mutation/DeleteRowsCoordinatorStandard.java @@ -105,7 +105,7 @@ public void deleteRows(PersistentCollection collection, Object key, SharedSes deletionCount++; } - MODEL_MUTATION_LOGGER.tracef( "Done deleting `%s` collection rows : %s", + MODEL_MUTATION_LOGGER.tracef( "Done deleting %s collection rows : %s", deletionCount, mutationTarget.getRolePath() ); } finally { diff --git a/hibernate-core/src/main/java/org/hibernate/persister/collection/mutation/DeleteRowsCoordinatorTablePerSubclass.java b/hibernate-core/src/main/java/org/hibernate/persister/collection/mutation/DeleteRowsCoordinatorTablePerSubclass.java index 820f4345a88b..705c125db538 100644 --- a/hibernate-core/src/main/java/org/hibernate/persister/collection/mutation/DeleteRowsCoordinatorTablePerSubclass.java +++ b/hibernate-core/src/main/java/org/hibernate/persister/collection/mutation/DeleteRowsCoordinatorTablePerSubclass.java @@ -108,7 +108,7 @@ public void deleteRows(PersistentCollection collection, Object key, SharedSes deletionCount++; } - MODEL_MUTATION_LOGGER.tracef( "Done deleting `%s` collection rows : %s", + MODEL_MUTATION_LOGGER.tracef( "Done deleting %s collection rows : %s", deletionCount, mutationTarget.getRolePath() ); } finally { diff --git a/hibernate-core/src/main/java/org/hibernate/persister/collection/mutation/InsertRowsCoordinatorStandard.java b/hibernate-core/src/main/java/org/hibernate/persister/collection/mutation/InsertRowsCoordinatorStandard.java index df3f08f22814..2382c70d9c8f 100644 --- a/hibernate-core/src/main/java/org/hibernate/persister/collection/mutation/InsertRowsCoordinatorStandard.java +++ b/hibernate-core/src/main/java/org/hibernate/persister/collection/mutation/InsertRowsCoordinatorStandard.java @@ -118,7 +118,7 @@ public void insertRows( entryCount++; } - MODEL_MUTATION_LOGGER.tracef( "Done inserting `%s` collection rows : %s", + MODEL_MUTATION_LOGGER.tracef( "Done inserting %s collection rows : %s", entryCount, mutationTarget.getRolePath() ); } diff --git a/hibernate-core/src/main/java/org/hibernate/persister/collection/mutation/InsertRowsCoordinatorTablePerSubclass.java b/hibernate-core/src/main/java/org/hibernate/persister/collection/mutation/InsertRowsCoordinatorTablePerSubclass.java index 1f5cb4032f82..ec9e72dddd46 100644 --- a/hibernate-core/src/main/java/org/hibernate/persister/collection/mutation/InsertRowsCoordinatorTablePerSubclass.java +++ b/hibernate-core/src/main/java/org/hibernate/persister/collection/mutation/InsertRowsCoordinatorTablePerSubclass.java @@ -127,7 +127,7 @@ public void insertRows( if ( loggerTraceEnabled ) { MODEL_MUTATION_LOGGER.tracef( - "Done inserting `%s` collection rows: %s", + "Done inserting %s collection rows: %s", entryCount, mutationTarget.getRolePath() ); diff --git a/hibernate-core/src/main/java/org/hibernate/persister/collection/mutation/RemoveCoordinatorStandard.java b/hibernate-core/src/main/java/org/hibernate/persister/collection/mutation/RemoveCoordinatorStandard.java index 7754abc0eac5..82f1cc64f3f2 100644 --- a/hibernate-core/src/main/java/org/hibernate/persister/collection/mutation/RemoveCoordinatorStandard.java +++ b/hibernate-core/src/main/java/org/hibernate/persister/collection/mutation/RemoveCoordinatorStandard.java @@ -120,10 +120,10 @@ private MutationOperationGroup buildOperationGroup() { assert mutationTarget.getTargetPart() != null; assert mutationTarget.getTargetPart().getKeyDescriptor() != null; - if ( MODEL_MUTATION_LOGGER.isTraceEnabled() ) { - MODEL_MUTATION_LOGGER.tracef( "Starting RemoveCoordinator#buildOperationGroup - %s", - mutationTarget.getRolePath() ); - } +// if ( MODEL_MUTATION_LOGGER.isTraceEnabled() ) { +// MODEL_MUTATION_LOGGER.tracef( "Starting RemoveCoordinator#buildOperationGroup - %s", +// mutationTarget.getRolePath() ); +// } final CollectionTableMapping tableMapping = mutationTarget.getCollectionTableMapping(); final MutatingTableReference tableReference = new MutatingTableReference( tableMapping ); diff --git a/hibernate-core/src/main/java/org/hibernate/persister/collection/mutation/RemoveCoordinatorTablePerSubclass.java b/hibernate-core/src/main/java/org/hibernate/persister/collection/mutation/RemoveCoordinatorTablePerSubclass.java index b0cb515d6a42..1d2e64d5d4f0 100644 --- a/hibernate-core/src/main/java/org/hibernate/persister/collection/mutation/RemoveCoordinatorTablePerSubclass.java +++ b/hibernate-core/src/main/java/org/hibernate/persister/collection/mutation/RemoveCoordinatorTablePerSubclass.java @@ -126,10 +126,10 @@ private MutationOperationGroup buildOperationGroup(EntityPersister elementPersis assert mutationTarget.getTargetPart() != null; assert mutationTarget.getTargetPart().getKeyDescriptor() != null; - if ( MODEL_MUTATION_LOGGER.isTraceEnabled() ) { - MODEL_MUTATION_LOGGER.tracef( "Starting RemoveCoordinator#buildOperationGroup - %s", - mutationTarget.getRolePath() ); - } +// if ( MODEL_MUTATION_LOGGER.isTraceEnabled() ) { +// MODEL_MUTATION_LOGGER.tracef( "Starting RemoveCoordinator#buildOperationGroup - %s", +// mutationTarget.getRolePath() ); +// } final CollectionTableMapping collectionTableMapping = mutationTarget.getCollectionTableMapping(); final MutatingTableReference tableReference = new MutatingTableReference( diff --git a/hibernate-core/src/main/java/org/hibernate/persister/entity/AbstractEntityPersister.java b/hibernate-core/src/main/java/org/hibernate/persister/entity/AbstractEntityPersister.java index 3af329a2b17c..93f7bdf3149a 100644 --- a/hibernate-core/src/main/java/org/hibernate/persister/entity/AbstractEntityPersister.java +++ b/hibernate-core/src/main/java/org/hibernate/persister/entity/AbstractEntityPersister.java @@ -305,6 +305,7 @@ import static org.hibernate.persister.entity.DiscriminatorHelper.NULL_DISCRIMINATOR; import static org.hibernate.pretty.MessageHelper.infoString; import static org.hibernate.sql.ast.spi.SqlExpressionResolver.createColumnReferenceKey; +import static org.hibernate.sql.model.ModelMutationLogging.MODEL_MUTATION_LOGGER; /** * Basic functionality for persisting an entity via JDBC, using either generated or custom SQL. @@ -496,14 +497,19 @@ public AbstractEntityPersister( : ImmutableEntityEntryFactory.INSTANCE; // Handle any filters applied to the class level - filterHelper = isNotEmpty( persistentClass.getFilters() ) ? new FilterHelper( - persistentClass.getFilters(), - getEntityNameByTableNameMap( - persistentClass, - factory.getSqlStringGenerationContext() - ), - factory - ) : null; + if ( isNotEmpty( persistentClass.getFilters() ) ) { + filterHelper = new FilterHelper( + persistentClass.getFilters(), + getEntityNameByTableNameMap( + persistentClass, + factory.getSqlStringGenerationContext() + ), + factory + ); + } + else { + filterHelper = null; + } // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ @@ -2670,13 +2676,13 @@ public ModelPart getIdentifierDescriptor() { } protected void logStaticSQL() { - if ( LOG.isDebugEnabled() ) { - LOG.debugf( "Static SQL for entity: %s", getEntityName() ); - for ( Map.Entry entry : lazyLoadPlanByFetchGroup.entrySet() ) { - LOG.debugf( " Lazy select (%s) : %s", entry.getKey(), entry.getValue().getJdbcSelect().getSqlString() ); + if ( MODEL_MUTATION_LOGGER.isTraceEnabled() ) { + MODEL_MUTATION_LOGGER.tracef( "Static SQL for entity: %s", getEntityName() ); + for ( var entry : lazyLoadPlanByFetchGroup.entrySet() ) { + MODEL_MUTATION_LOGGER.tracef( " Lazy select (%s) : %s", entry.getKey(), entry.getValue().getJdbcSelect().getSqlString() ); } if ( sqlVersionSelectString != null ) { - LOG.debugf( " Version select: %s", sqlVersionSelectString ); + MODEL_MUTATION_LOGGER.tracef( " Version select: %s", sqlVersionSelectString ); } { @@ -2685,7 +2691,7 @@ protected void logStaticSQL() { for ( int i = 0; i < staticInsertGroup.getNumberOfOperations(); i++ ) { final MutationOperation mutation = staticInsertGroup.getOperation( i ); if ( mutation instanceof JdbcOperation jdbcOperation ) { - LOG.debugf( " Insert (%s): %s", i, jdbcOperation.getSqlString() ); + MODEL_MUTATION_LOGGER.tracef( " Insert (%s): %s", i, jdbcOperation.getSqlString() ); } } } @@ -2697,7 +2703,7 @@ protected void logStaticSQL() { for ( int i = 0; i < staticUpdateGroup.getNumberOfOperations(); i++ ) { final MutationOperation mutation = staticUpdateGroup.getOperation( i ); if ( mutation instanceof JdbcOperation jdbcOperation ) { - LOG.debugf( " Update (%s): %s", i, jdbcOperation.getSqlString() ); + MODEL_MUTATION_LOGGER.tracef( " Update (%s): %s", i, jdbcOperation.getSqlString() ); } } } @@ -2709,7 +2715,7 @@ protected void logStaticSQL() { for ( int i = 0; i < staticDeleteGroup.getNumberOfOperations(); i++ ) { final MutationOperation mutation = staticDeleteGroup.getOperation( i ); if ( mutation instanceof JdbcOperation jdbcOperation ) { - LOG.debugf( " Delete (%s): %s", i, jdbcOperation.getSqlString() ); + MODEL_MUTATION_LOGGER.tracef( " Delete (%s): %s", i, jdbcOperation.getSqlString() ); } } } @@ -4386,7 +4392,7 @@ public void processInsertGeneratedProperties( GeneratedValues generatedValues, SharedSessionContractImplementor session) { if ( insertGeneratedValuesProcessor == null ) { - throw new UnsupportedOperationException( "Entity has no insert-generated properties - `" + getEntityName() + "`" ); + throw new UnsupportedOperationException( "Entity has no insert-generated properties - '" + getEntityName() + "'" ); } insertGeneratedValuesProcessor.processGeneratedValues( entity, id, state, generatedValues, session ); } @@ -4424,7 +4430,7 @@ public void processUpdateGeneratedProperties( GeneratedValues generatedValues, SharedSessionContractImplementor session) { if ( updateGeneratedValuesProcessor == null ) { - throw new AssertionFailure( "Entity has no update-generated properties - `" + getEntityName() + "`" ); + throw new AssertionFailure( "Entity has no update-generated properties - '" + getEntityName() + "'" ); } updateGeneratedValuesProcessor.processGeneratedValues( entity, id, state, generatedValues, session ); } @@ -5672,7 +5678,6 @@ public AttributeMapping findAttributeMapping(String name) { @Override public ModelPart findSubPart(String name, EntityMappingType treatTargetType) { - LOG.tracef( "#findSubPart(`%s`)", name ); if ( EntityDiscriminatorMapping.matchesRoleName( name ) ) { return discriminatorMapping; diff --git a/hibernate-core/src/main/java/org/hibernate/persister/entity/EntityPropertyMapping.java b/hibernate-core/src/main/java/org/hibernate/persister/entity/EntityPropertyMapping.java index 266a06ab7ccc..e6ed1c6536b8 100644 --- a/hibernate-core/src/main/java/org/hibernate/persister/entity/EntityPropertyMapping.java +++ b/hibernate-core/src/main/java/org/hibernate/persister/entity/EntityPropertyMapping.java @@ -95,14 +95,15 @@ public String[] getColumnNames(String propertyName) { } private void logDuplicateRegistration(String path, Type existingType, Type type) { - if ( LOG.isTraceEnabled() ) { - LOG.tracev( - "Skipping duplicate registration of path [{0}], existing type = [{1}], incoming type = [{2}]", - path, - existingType, - type - ); - } + // Disabled because this resulted in many useless messages +// if ( LOG.isTraceEnabled() ) { +// LOG.tracev( +// "Skipping duplicate registration of path [{0}], existing type = [{1}], incoming type = [{2}]", +// path, +// existingType, +// type +// ); +// } } private void logIncompatibleRegistration(String path, Type existingType, Type type) { diff --git a/hibernate-core/src/main/java/org/hibernate/query/hql/internal/BasicDotIdentifierConsumer.java b/hibernate-core/src/main/java/org/hibernate/query/hql/internal/BasicDotIdentifierConsumer.java index ac9146e5ca0d..1cd1d5d0e2ac 100644 --- a/hibernate-core/src/main/java/org/hibernate/query/hql/internal/BasicDotIdentifierConsumer.java +++ b/hibernate-core/src/main/java/org/hibernate/query/hql/internal/BasicDotIdentifierConsumer.java @@ -27,7 +27,6 @@ import org.hibernate.type.descriptor.java.EnumJavaType; import org.hibernate.type.descriptor.java.JavaType; -import static org.hibernate.query.hql.HqlLogging.QUERY_LOGGER; /** * A {@link DotIdentifierConsumer} used to interpret paths outside any diff --git a/hibernate-core/src/main/java/org/hibernate/query/hql/internal/SemanticQueryBuilder.java b/hibernate-core/src/main/java/org/hibernate/query/hql/internal/SemanticQueryBuilder.java index db5f9b58e394..be7845bc1ab4 100644 --- a/hibernate-core/src/main/java/org/hibernate/query/hql/internal/SemanticQueryBuilder.java +++ b/hibernate-core/src/main/java/org/hibernate/query/hql/internal/SemanticQueryBuilder.java @@ -2145,7 +2145,7 @@ public final SqmCrossJoin visitCrossJoin(HqlParser.CrossJoinContext ctx) { protected void consumeCrossJoin(HqlParser.CrossJoinContext parserJoin, SqmRoot sqmRoot) { final String name = getEntityName( parserJoin.entityName() ); - SqmTreeCreationLogger.LOGGER.tracef( "Handling root path - %s", name ); +// SqmTreeCreationLogger.LOGGER.tracef( "Handling root path - %s", name ); final EntityDomainType entityDescriptor = getJpaMetamodel().resolveHqlEntityReference( name ); diff --git a/hibernate-core/src/main/java/org/hibernate/query/hql/internal/SqmTreeCreationHelper.java b/hibernate-core/src/main/java/org/hibernate/query/hql/internal/SqmTreeCreationHelper.java index 2e71a0dac7c5..27903147b862 100644 --- a/hibernate-core/src/main/java/org/hibernate/query/hql/internal/SqmTreeCreationHelper.java +++ b/hibernate-core/src/main/java/org/hibernate/query/hql/internal/SqmTreeCreationHelper.java @@ -10,7 +10,6 @@ import org.hibernate.AssertionFailure; import org.hibernate.grammars.hql.HqlParser; import org.hibernate.jpa.spi.JpaCompliance; -import org.hibernate.query.sqm.SqmTreeCreationLogger; import org.hibernate.query.sqm.StrictJpaComplianceViolation; import org.hibernate.query.sqm.tree.SqmJoinType; import org.hibernate.query.sqm.tree.from.SqmEntityJoin; @@ -139,7 +138,9 @@ public static void handleRootAsCrossJoin( //noinspection unchecked final SqmRoot sqmRoot = (SqmRoot) fromRootContext.accept( sqmBuilder ); - SqmTreeCreationLogger.LOGGER.tracef( "Handling secondary root path as cross-join - %s", sqmRoot.getEntityName() ); + +// SqmTreeCreationLogger.LOGGER.tracef( "Handling secondary root path as cross-join - %s", sqmRoot.getEntityName() ); + final SqmEntityJoin pseudoCrossJoin = new SqmEntityJoin<>( sqmRoot.getManagedType(), extractAlias( fromRootContext.variable(), sqmBuilder ), diff --git a/hibernate-core/src/main/java/org/hibernate/query/internal/QueryInterpretationCacheStandardImpl.java b/hibernate-core/src/main/java/org/hibernate/query/internal/QueryInterpretationCacheStandardImpl.java index 14c0e646ca86..ae8c3d182be6 100644 --- a/hibernate-core/src/main/java/org/hibernate/query/internal/QueryInterpretationCacheStandardImpl.java +++ b/hibernate-core/src/main/java/org/hibernate/query/internal/QueryInterpretationCacheStandardImpl.java @@ -47,7 +47,7 @@ public class QueryInterpretationCacheStandardImpl implements QueryInterpretation private StatisticsImplementor statistics; public QueryInterpretationCacheStandardImpl(int maxQueryPlanCount, ServiceRegistry serviceRegistry) { - log.tracef( "Starting QueryInterpretationCache (size %s)", maxQueryPlanCount ); + log.tracef( "Starting query interpretation cache (size %s)", maxQueryPlanCount ); final InternalCacheFactory cacheFactory = serviceRegistry.requireService( InternalCacheFactory.class ); this.queryPlanCache = cacheFactory.createInternalCache( maxQueryPlanCount ); this.hqlInterpretationCache = cacheFactory.createInternalCache( maxQueryPlanCount ); @@ -76,7 +76,7 @@ private StatisticsImplementor getStatistics() { public SelectQueryPlan resolveSelectQueryPlan( Key key, Supplier> creator) { - log.tracef( "Resolving cached QueryPlan for [%s]", key ); + log.tracef( "Resolving cached query plan for [%s]", key ); final StatisticsImplementor statistics = getStatistics(); final boolean stats = statistics.isStatisticsEnabled(); @@ -111,7 +111,7 @@ public HqlInterpretation resolveHqlInterpretation( String queryString, Class expectedResultType, HqlTranslator translator) { - log.tracef( "Resolving HQL interpretation for '%s'", queryString ); + log.tracef( "Resolving HQL interpretation for [%s]", queryString ); final StatisticsImplementor statistics = getStatistics(); final Object cacheKey = expectedResultType != null @@ -182,7 +182,7 @@ protected static HqlInterpretation createHqlInterpretation( public ParameterInterpretation resolveNativeQueryParameters( String queryString, Function creator) { - log.tracef( "Resolving native query parameters for '%s'", queryString ); + log.tracef( "Resolving native query parameters for [%s]", queryString ); return nativeQueryParamCache.computeIfAbsent( queryString, creator ); } @@ -193,7 +193,7 @@ public boolean isEnabled() { @Override public void close() { - log.trace( "Closing QueryInterpretationCache" ); + log.trace( "Destroying query interpretation cache" ); hqlInterpretationCache.clear(); nativeQueryParamCache.clear(); queryPlanCache.clear(); diff --git a/hibernate-core/src/main/java/org/hibernate/query/sqm/function/NamedSqmFunctionDescriptor.java b/hibernate-core/src/main/java/org/hibernate/query/sqm/function/NamedSqmFunctionDescriptor.java index 4ab85b5e352e..80ea1ae109f2 100644 --- a/hibernate-core/src/main/java/org/hibernate/query/sqm/function/NamedSqmFunctionDescriptor.java +++ b/hibernate-core/src/main/java/org/hibernate/query/sqm/function/NamedSqmFunctionDescriptor.java @@ -106,7 +106,9 @@ public String getName() { @Override public String getArgumentListSignature() { - return argumentListSignature == null ? super.getArgumentListSignature() : argumentListSignature; + return argumentListSignature == null + ? super.getArgumentListSignature() + : argumentListSignature; } @Override @@ -246,7 +248,7 @@ private void render( public String toString() { return String.format( Locale.ROOT, - "NamedSqmFunctionTemplate(%s)", + "NamedSqmFunctionDescriptor(%s)", functionName ); } diff --git a/hibernate-core/src/main/java/org/hibernate/query/sqm/function/PatternBasedSqmFunctionDescriptor.java b/hibernate-core/src/main/java/org/hibernate/query/sqm/function/PatternBasedSqmFunctionDescriptor.java index 9af06923d6ba..0ddd5aad882b 100644 --- a/hibernate-core/src/main/java/org/hibernate/query/sqm/function/PatternBasedSqmFunctionDescriptor.java +++ b/hibernate-core/src/main/java/org/hibernate/query/sqm/function/PatternBasedSqmFunctionDescriptor.java @@ -17,6 +17,7 @@ import org.hibernate.sql.ast.tree.select.SortSpecification; import java.util.List; +import java.util.Locale; /** * Support for HQL functions that have different representations @@ -115,6 +116,18 @@ public void render( @Override public String getArgumentListSignature() { - return argumentListSignature == null ? super.getArgumentListSignature() : argumentListSignature; + return argumentListSignature == null + ? super.getArgumentListSignature() + : argumentListSignature; } + + @Override + public String toString() { + return String.format( + Locale.ROOT, + "PatternBasedSqmFunctionDescriptor(%s)", + getName() + ); + } + } diff --git a/hibernate-core/src/main/java/org/hibernate/query/sqm/internal/SqmInterpretationsKey.java b/hibernate-core/src/main/java/org/hibernate/query/sqm/internal/SqmInterpretationsKey.java index 3db3cb126864..f48e2875662d 100644 --- a/hibernate-core/src/main/java/org/hibernate/query/sqm/internal/SqmInterpretationsKey.java +++ b/hibernate-core/src/main/java/org/hibernate/query/sqm/internal/SqmInterpretationsKey.java @@ -134,4 +134,9 @@ public boolean equals(Object other) { public int hashCode() { return hashCode; } + + @Override + public String toString() { + return query.toString() + " : " + resultType.getSimpleName(); + } } diff --git a/hibernate-core/src/main/java/org/hibernate/query/sqm/internal/SqmTreePrinter.java b/hibernate-core/src/main/java/org/hibernate/query/sqm/internal/SqmTreePrinter.java index 41b6f501f7bb..631b57978d8d 100644 --- a/hibernate-core/src/main/java/org/hibernate/query/sqm/internal/SqmTreePrinter.java +++ b/hibernate-core/src/main/java/org/hibernate/query/sqm/internal/SqmTreePrinter.java @@ -151,7 +151,7 @@ public static void logTree(SqmQuerySpec sqmQuerySpec, String header) { final String title = header != null ? header : "SqmQuerySpec Tree"; - LOGGER.tracef( "%s :%n%s", title, treePrinter.buffer.toString() ); + LOGGER.tracef( "%s:%n%s", title, treePrinter.buffer.toString() ); } public static void logTree(SqmStatement sqmStatement) { @@ -174,7 +174,7 @@ else if ( sqmStatement instanceof SqmInsertSelectStatement statement ) { printer.visitInsertSelectStatement( statement ); } - LOGGER.tracef( "SqmStatement Tree :%n%s", printer.buffer.toString() ); + LOGGER.tracef( "SqmStatement Tree:%n%s", printer.buffer.toString() ); } private final StringBuffer buffer = new StringBuffer(); @@ -539,7 +539,7 @@ public Object visitFromClause(SqmFromClause fromClause) { public Object visitRootPath(SqmRoot sqmRoot) { processStanza( "root", - "`" + sqmRoot.getNavigablePath() + "`", + "'" + sqmRoot.getNavigablePath() + "'", () -> processJoins( sqmRoot ) ); @@ -550,7 +550,7 @@ public Object visitRootPath(SqmRoot sqmRoot) { public Object visitRootDerived(SqmDerivedRoot sqmRoot) { processStanza( "derived", - "`" + sqmRoot.getNavigablePath() + "`", + "'" + sqmRoot.getNavigablePath() + "'", () -> processJoins( sqmRoot ) ); return null; @@ -560,7 +560,7 @@ public Object visitRootDerived(SqmDerivedRoot sqmRoot) { public Object visitRootFunction(SqmFunctionRoot sqmRoot) { processStanza( "derived", - "`" + sqmRoot.getNavigablePath() + "`", + "'" + sqmRoot.getNavigablePath() + "'", () -> processJoins( sqmRoot ) ); return null; @@ -570,7 +570,7 @@ public Object visitRootFunction(SqmFunctionRoot sqmRoot) { public Object visitRootCte(SqmCteRoot sqmRoot) { processStanza( "cte", - "`" + sqmRoot.getNavigablePath() + "`", + "'" + sqmRoot.getNavigablePath() + "'", () -> processJoins( sqmRoot ) ); return null; @@ -591,7 +591,7 @@ private void processJoins(SqmFrom sqmFrom) { public Object visitCrossJoin(SqmCrossJoin joinedFromElement) { processStanza( "cross", - "`" + joinedFromElement.getNavigablePath() + "`", + "'" + joinedFromElement.getNavigablePath() + "'", () -> processJoins( joinedFromElement ) ); @@ -602,7 +602,7 @@ public Object visitCrossJoin(SqmCrossJoin joinedFromElement) { public Object visitPluralPartJoin(SqmPluralPartJoin joinedFromElement) { processStanza( "plural-part", - "`" + joinedFromElement.getNavigablePath() + "`", + "'" + joinedFromElement.getNavigablePath() + "'", () -> processJoins( joinedFromElement ) ); @@ -626,12 +626,12 @@ private void processJoinPredicate(SqmJoin joinedFromElement) { @Override public Object visitQualifiedEntityJoin(SqmEntityJoin joinedFromElement) { if ( inJoinPredicate ) { - logWithIndentation( "-> [joined-path] - `%s`", joinedFromElement.getNavigablePath() ); + logWithIndentation( "-> [joined-path] - '%s'", joinedFromElement.getNavigablePath() ); } else { processStanza( "entity", - "`" + joinedFromElement.getNavigablePath() + "`", + "'" + joinedFromElement.getNavigablePath() + "'", () -> { processJoinPredicate( joinedFromElement ); processJoins( joinedFromElement ); @@ -644,12 +644,12 @@ public Object visitQualifiedEntityJoin(SqmEntityJoin joinedFromElement) { @Override public Object visitQualifiedAttributeJoin(SqmAttributeJoin joinedFromElement) { if ( inJoinPredicate ) { - logWithIndentation( "-> [joined-path] - `%s`", joinedFromElement.getNavigablePath() ); + logWithIndentation( "-> [joined-path] - '%s'", joinedFromElement.getNavigablePath() ); } else { processStanza( "attribute", - "`" + joinedFromElement.getNavigablePath() + "`", + "'" + joinedFromElement.getNavigablePath() + "'", () -> { logIndented( "[fetched = " + joinedFromElement.isFetched() + ']' ); @@ -664,12 +664,12 @@ public Object visitQualifiedAttributeJoin(SqmAttributeJoin joinedFromElemen @Override public Object visitQualifiedDerivedJoin(SqmDerivedJoin joinedFromElement) { if ( inJoinPredicate ) { - logWithIndentation( "-> [joined-path] - `%s`", joinedFromElement.getNavigablePath() ); + logWithIndentation( "-> [joined-path] - '%s'", joinedFromElement.getNavigablePath() ); } else { processStanza( "derived", - "`" + joinedFromElement.getNavigablePath() + "`", + "'" + joinedFromElement.getNavigablePath() + "'", () -> { processJoinPredicate( joinedFromElement ); processJoins( joinedFromElement ); @@ -682,12 +682,12 @@ public Object visitQualifiedDerivedJoin(SqmDerivedJoin joinedFromElement) { @Override public Object visitQualifiedFunctionJoin(SqmFunctionJoin joinedFromElement) { if ( inJoinPredicate ) { - logWithIndentation( "-> [joined-path] - `%s`", joinedFromElement.getNavigablePath() ); + logWithIndentation( "-> [joined-path] - '%s'", joinedFromElement.getNavigablePath() ); } else { processStanza( "derived", - "`" + joinedFromElement.getNavigablePath() + "`", + "'" + joinedFromElement.getNavigablePath() + "'", () -> { processJoinPredicate( joinedFromElement ); processJoins( joinedFromElement ); @@ -700,12 +700,12 @@ public Object visitQualifiedFunctionJoin(SqmFunctionJoin joinedFromElement) { @Override public Object visitQualifiedCteJoin(SqmCteJoin joinedFromElement) { if ( inJoinPredicate ) { - logWithIndentation( "-> [joined-path] - `%s`", joinedFromElement.getNavigablePath() ); + logWithIndentation( "-> [joined-path] - '%s'", joinedFromElement.getNavigablePath() ); } else { processStanza( "cte", - "`" + joinedFromElement.getNavigablePath() + "`", + "'" + joinedFromElement.getNavigablePath() + "'", () -> { processJoinPredicate( joinedFromElement ); processJoins( joinedFromElement ); @@ -717,56 +717,56 @@ public Object visitQualifiedCteJoin(SqmCteJoin joinedFromElement) { @Override public Object visitBasicValuedPath(SqmBasicValuedSimplePath path) { - logWithIndentation( "-> [basic-path] - `%s`", path.getNavigablePath() ); + logWithIndentation( "-> [basic-path] - '%s'", path.getNavigablePath() ); return null; } @Override public Object visitEmbeddableValuedPath(SqmEmbeddedValuedSimplePath path) { - logWithIndentation( "-> [embedded-path] - `%s`", path.getNavigablePath() ); + logWithIndentation( "-> [embedded-path] - '%s'", path.getNavigablePath() ); return null; } @Override public Object visitAnyValuedValuedPath(SqmAnyValuedSimplePath path) { - logWithIndentation( "-> [any-path] - `%s`", path.getNavigablePath() ); + logWithIndentation( "-> [any-path] - '%s'", path.getNavigablePath() ); return null; } @Override public Object visitNonAggregatedCompositeValuedPath(NonAggregatedCompositeSimplePath path) { - logWithIndentation( "-> [non-aggregated-composite-path] - `%s`", path.getNavigablePath() ); + logWithIndentation( "-> [non-aggregated-composite-path] - '%s'", path.getNavigablePath() ); return null; } @Override public Object visitFkExpression(SqmFkExpression fkExpression) { - logWithIndentation( "-> [fk-ref] - `%s`", fkExpression.getLhs().getNavigablePath() ); + logWithIndentation( "-> [fk-ref] - '%s'", fkExpression.getLhs().getNavigablePath() ); return null; } @Override public Object visitDiscriminatorPath(DiscriminatorSqmPath sqmPath) { - logWithIndentation( "-> [discriminator-path] - `%s`", sqmPath.getNavigablePath() ); + logWithIndentation( "-> [discriminator-path] - '%s'", sqmPath.getNavigablePath() ); return null; } @Override public Object visitEntityValuedPath(SqmEntityValuedSimplePath path) { - logWithIndentation( "-> [entity-path] - `%s`", path.getNavigablePath() ); + logWithIndentation( "-> [entity-path] - '%s'", path.getNavigablePath() ); return null; } @Override public Object visitPluralValuedPath(SqmPluralValuedSimplePath path) { - logWithIndentation( "-> [plural-path] - `%s`", path.getNavigablePath() ); + logWithIndentation( "-> [plural-path] - '%s'", path.getNavigablePath() ); return null; } diff --git a/hibernate-core/src/main/java/org/hibernate/query/sqm/sql/BaseSqmToSqlAstConverter.java b/hibernate-core/src/main/java/org/hibernate/query/sqm/sql/BaseSqmToSqlAstConverter.java index ed393988418a..c7aacdeacecc 100644 --- a/hibernate-core/src/main/java/org/hibernate/query/sqm/sql/BaseSqmToSqlAstConverter.java +++ b/hibernate-core/src/main/java/org/hibernate/query/sqm/sql/BaseSqmToSqlAstConverter.java @@ -295,7 +295,6 @@ import org.hibernate.type.internal.BasicTypeImpl; import org.hibernate.type.spi.TypeConfiguration; import org.hibernate.usertype.UserVersionType; -import org.jboss.logging.Logger; import java.math.BigDecimal; import java.math.BigInteger; @@ -353,7 +352,7 @@ public abstract class BaseSqmToSqlAstConverter extends BaseSemanticQueryWalker implements SqmTranslator, DomainResultCreationState, JdbcTypeIndicators { - private static final Logger log = Logger.getLogger( BaseSqmToSqlAstConverter.class ); +// private static final Logger log = Logger.getLogger( BaseSqmToSqlAstConverter.class ); private final SqlAstCreationContext creationContext; private final boolean jpaQueryComplianceEnabled; @@ -2481,11 +2480,11 @@ public Void visitFromClause(SqmFromClause sqmFromClause) { } protected void consumeFromClauseCorrelatedRoot(SqmRoot sqmRoot) { - log.tracef( "Resolving SqmRoot [%s] to TableGroup", sqmRoot ); +// log.tracef( "Resolving SqmRoot [%s] to TableGroup", sqmRoot ); final FromClauseIndex fromClauseIndex = getFromClauseIndex(); - if ( fromClauseIndex.isResolved( sqmRoot ) ) { - log.tracef( "Already resolved SqmRoot [%s] to TableGroup", sqmRoot ); - } +// if ( fromClauseIndex.isResolved( sqmRoot ) ) { +// log.tracef( "Already resolved SqmRoot [%s] to TableGroup", sqmRoot ); +// } final TableGroup tableGroup; if ( !sqmRoot.isCorrelated() ) { return; @@ -2572,7 +2571,7 @@ protected void consumeFromClauseCorrelatedRoot(SqmRoot sqmRoot) { // Any table group joins added to the correlated table group are added to the query spec // as roots anyway, so nothing to worry about - log.tracef( "Resolved SqmRoot [%s] to correlated TableGroup [%s]", sqmRoot, tableGroup ); +// log.tracef( "Resolved SqmRoot [%s] to correlated TableGroup [%s]", sqmRoot, tableGroup ); consumeExplicitJoins( from, tableGroup ); return; } @@ -2641,7 +2640,7 @@ protected void consumeFromClauseCorrelatedRoot(SqmRoot sqmRoot) { } } - log.tracef( "Resolved SqmRoot [%s] to new TableGroup [%s]", sqmRoot, tableGroup ); +// log.tracef( "Resolved SqmRoot [%s] to new TableGroup [%s]", sqmRoot, tableGroup ); fromClauseIndex.register( sqmRoot, tableGroup ); currentQuerySpec.getFromClause().addRoot( tableGroup ); @@ -2650,11 +2649,11 @@ protected void consumeFromClauseCorrelatedRoot(SqmRoot sqmRoot) { } protected void consumeFromClauseRoot(SqmRoot sqmRoot) { - log.tracef( "Resolving SqmRoot [%s] to TableGroup", sqmRoot ); +// log.tracef( "Resolving SqmRoot [%s] to TableGroup", sqmRoot ); final FromClauseIndex fromClauseIndex = getFromClauseIndex(); - if ( fromClauseIndex.isResolved( sqmRoot ) ) { - log.tracef( "Already resolved SqmRoot [%s] to TableGroup", sqmRoot ); - } +// if ( fromClauseIndex.isResolved( sqmRoot ) ) { +// log.tracef( "Already resolved SqmRoot [%s] to TableGroup", sqmRoot ); +// } if ( sqmRoot.isCorrelated() ) { return; } @@ -2731,7 +2730,7 @@ else if ( sqmRoot instanceof SqmCteRoot cteRoot ) { ); } - log.tracef( "Resolved SqmRoot [%s] to new TableGroup [%s]", sqmRoot, tableGroup ); +// log.tracef( "Resolved SqmRoot [%s] to new TableGroup [%s]", sqmRoot, tableGroup ); registerSqmFromTableGroup( sqmRoot, tableGroup ); currentQueryNodeProcessingState.getFromClause().addRoot( tableGroup ); @@ -2815,9 +2814,9 @@ private void consumeJoins(SqmRoot sqmRoot, FromClauseIndex fromClauseIndex, T consumeExplicitJoins( sqmRoot, tableGroup ); } else { - if ( log.isTraceEnabled() ) { - log.tracef( "Visiting explicit joins for `%s`", sqmRoot.getNavigablePath() ); - } +// if ( log.isTraceEnabled() ) { +// log.tracef( "Visiting explicit joins for '%s'", sqmRoot.getNavigablePath() ); +// } TableGroup lastTableGroup = tableGroup; for ( SqmJoin join : sqmRoot.getOrderedJoins() ) { final TableGroup ownerTableGroup; @@ -3133,9 +3132,9 @@ protected void pruneTableGroupJoins() { } protected void consumeExplicitJoins(SqmFrom sqmFrom, TableGroup lhsTableGroup) { - if ( log.isTraceEnabled() ) { - log.tracef( "Visiting explicit joins for `%s`", sqmFrom.getNavigablePath() ); - } +// if ( log.isTraceEnabled() ) { +// log.tracef( "Visiting explicit joins for '%s'", sqmFrom.getNavigablePath() ); +// } sqmFrom.visitSqmJoins( sqmJoin -> { final TableGroup actualTableGroup = getActualTableGroup( lhsTableGroup, sqmJoin ); @@ -3891,7 +3890,7 @@ private void registerPluralTableGroupParts(NavigablePath navigablePath, TableGro public Expression visitRootPath(SqmRoot sqmRoot) { final TableGroup resolved = getFromClauseAccess().findTableGroup( sqmRoot.getNavigablePath() ); if ( resolved != null ) { - log.tracef( "SqmRoot [%s] resolved to existing TableGroup [%s]", sqmRoot, resolved ); +// log.tracef( "SqmRoot [%s] resolved to existing TableGroup [%s]", sqmRoot, resolved ); return visitTableGroup( resolved, sqmRoot ); } @@ -3902,7 +3901,7 @@ public Expression visitRootPath(SqmRoot sqmRoot) { public Object visitRootDerived(SqmDerivedRoot sqmRoot) { final TableGroup resolved = getFromClauseAccess().findTableGroup( sqmRoot.getNavigablePath() ); if ( resolved != null ) { - log.tracef( "SqmDerivedRoot [%s] resolved to existing TableGroup [%s]", sqmRoot, resolved ); +// log.tracef( "SqmDerivedRoot [%s] resolved to existing TableGroup [%s]", sqmRoot, resolved ); return visitTableGroup( resolved, sqmRoot ); } @@ -3913,7 +3912,7 @@ public Object visitRootDerived(SqmDerivedRoot sqmRoot) { public Object visitRootFunction(SqmFunctionRoot sqmRoot) { final TableGroup resolved = getFromClauseAccess().findTableGroup( sqmRoot.getNavigablePath() ); if ( resolved != null ) { - log.tracef( "SqmFunctionRoot [%s] resolved to existing TableGroup [%s]", sqmRoot, resolved ); +// log.tracef( "SqmFunctionRoot [%s] resolved to existing TableGroup [%s]", sqmRoot, resolved ); return visitTableGroup( resolved, sqmRoot ); } @@ -3924,7 +3923,7 @@ public Object visitRootFunction(SqmFunctionRoot sqmRoot) { public Object visitRootCte(SqmCteRoot sqmRoot) { final TableGroup resolved = getFromClauseAccess().findTableGroup( sqmRoot.getNavigablePath() ); if ( resolved != null ) { - log.tracef( "SqmCteRoot [%s] resolved to existing TableGroup [%s]", sqmRoot, resolved ); +// log.tracef( "SqmCteRoot [%s] resolved to existing TableGroup [%s]", sqmRoot, resolved ); return visitTableGroup( resolved, sqmRoot ); } @@ -3935,7 +3934,7 @@ public Object visitRootCte(SqmCteRoot sqmRoot) { public Expression visitQualifiedAttributeJoin(SqmAttributeJoin sqmJoin) { final TableGroup existing = getFromClauseAccess().findTableGroup( sqmJoin.getNavigablePath() ); if ( existing != null ) { - log.tracef( "SqmAttributeJoin [%s] resolved to existing TableGroup [%s]", sqmJoin, existing ); +// log.tracef( "SqmAttributeJoin [%s] resolved to existing TableGroup [%s]", sqmJoin, existing ); return visitTableGroup( existing, sqmJoin ); } @@ -3946,7 +3945,7 @@ public Expression visitQualifiedAttributeJoin(SqmAttributeJoin sqmJoin) { public Expression visitQualifiedDerivedJoin(SqmDerivedJoin sqmJoin) { final TableGroup existing = getFromClauseAccess().findTableGroup( sqmJoin.getNavigablePath() ); if ( existing != null ) { - log.tracef( "SqmDerivedJoin [%s] resolved to existing TableGroup [%s]", sqmJoin, existing ); +// log.tracef( "SqmDerivedJoin [%s] resolved to existing TableGroup [%s]", sqmJoin, existing ); return visitTableGroup( existing, sqmJoin ); } @@ -3957,7 +3956,7 @@ public Expression visitQualifiedDerivedJoin(SqmDerivedJoin sqmJoin) { public Object visitQualifiedFunctionJoin(SqmFunctionJoin sqmJoin) { final TableGroup existing = getFromClauseAccess().findTableGroup( sqmJoin.getNavigablePath() ); if ( existing != null ) { - log.tracef( "SqmFunctionJoin [%s] resolved to existing TableGroup [%s]", sqmJoin, existing ); +// log.tracef( "SqmFunctionJoin [%s] resolved to existing TableGroup [%s]", sqmJoin, existing ); return visitTableGroup( existing, sqmJoin ); } @@ -3968,7 +3967,7 @@ public Object visitQualifiedFunctionJoin(SqmFunctionJoin sqmJoin) { public Object visitQualifiedCteJoin(SqmCteJoin sqmJoin) { final TableGroup existing = getFromClauseAccess().findTableGroup( sqmJoin.getNavigablePath() ); if ( existing != null ) { - log.tracef( "SqmCteJoin [%s] resolved to existing TableGroup [%s]", sqmJoin, existing ); +// log.tracef( "SqmCteJoin [%s] resolved to existing TableGroup [%s]", sqmJoin, existing ); return visitTableGroup( existing, sqmJoin ); } @@ -3979,7 +3978,7 @@ public Object visitQualifiedCteJoin(SqmCteJoin sqmJoin) { public Expression visitCrossJoin(SqmCrossJoin sqmJoin) { final TableGroup existing = getFromClauseAccess().findTableGroup( sqmJoin.getNavigablePath() ); if ( existing != null ) { - log.tracef( "SqmCrossJoin [%s] resolved to existing TableGroup [%s]", sqmJoin, existing ); +// log.tracef( "SqmCrossJoin [%s] resolved to existing TableGroup [%s]", sqmJoin, existing ); return visitTableGroup( existing, sqmJoin ); } @@ -3990,7 +3989,7 @@ public Expression visitCrossJoin(SqmCrossJoin sqmJoin) { public Object visitPluralPartJoin(SqmPluralPartJoin sqmJoin) { final TableGroup existing = getFromClauseAccess().findTableGroup( sqmJoin.getNavigablePath() ); if ( existing != null ) { - log.tracef( "SqmPluralPartJoin [%s] resolved to existing TableGroup [%s]", sqmJoin, existing ); +// log.tracef( "SqmPluralPartJoin [%s] resolved to existing TableGroup [%s]", sqmJoin, existing ); return visitTableGroup( existing, sqmJoin ); } @@ -4001,7 +4000,7 @@ public Object visitPluralPartJoin(SqmPluralPartJoin sqmJoin) { public Expression visitQualifiedEntityJoin(SqmEntityJoin sqmJoin) { final TableGroup existing = getFromClauseAccess().findTableGroup( sqmJoin.getNavigablePath() ); if ( existing != null ) { - log.tracef( "SqmEntityJoin [%s] resolved to existing TableGroup [%s]", sqmJoin, existing ); +// log.tracef( "SqmEntityJoin [%s] resolved to existing TableGroup [%s]", sqmJoin, existing ); return visitTableGroup( existing, sqmJoin ); } @@ -4504,7 +4503,7 @@ public Expression visitFunctionPath(SqmFunctionPath functionPath) { public Expression visitCorrelation(SqmCorrelation correlation) { final TableGroup resolved = getFromClauseAccess().findTableGroup( correlation.getNavigablePath() ); if ( resolved != null ) { - log.tracef( "SqmCorrelation [%s] resolved to existing TableGroup [%s]", correlation, resolved ); +// log.tracef( "SqmCorrelation [%s] resolved to existing TableGroup [%s]", correlation, resolved ); return visitTableGroup( resolved, correlation ); } throw new InterpretationException( "SqmCorrelation not yet resolved to TableGroup" ); @@ -4515,7 +4514,7 @@ public Expression visitTreatedPath(SqmTreatedPath sqmTreatedPath) { prepareReusablePath( sqmTreatedPath, () -> null ); final TableGroup resolved = getFromClauseAccess().findTableGroup( sqmTreatedPath.getNavigablePath() ); if ( resolved != null ) { - log.tracef( "SqmTreatedPath [%s] resolved to existing TableGroup [%s]", sqmTreatedPath, resolved ); +// log.tracef( "SqmTreatedPath [%s] resolved to existing TableGroup [%s]", sqmTreatedPath, resolved ); return visitTableGroup( resolved, sqmTreatedPath ); } @@ -5807,7 +5806,7 @@ private MappingModelExpressible determineValueMapping(SqmExpression sqmExp } if ( sqmExpression instanceof SqmPath ) { - log.tracef( "Determining mapping-model type for SqmPath: %s ", sqmExpression ); +// log.tracef( "Determining mapping-model type for SqmPath: %s ", sqmExpression ); final MappingModelExpressible mappingModelExpressible = resolveMappingModelExpressible( sqmExpression, domainModel, fromClauseIndex::findTableGroup ); if ( mappingModelExpressible != null ) { @@ -5880,7 +5879,7 @@ private MappingModelExpressible determineValueMapping(SqmExpression sqmExp } } - log.tracef( "Determining mapping-model type for generalized SqmExpression: %s", sqmExpression ); +// log.tracef( "Determining mapping-model type for generalized SqmExpression: %s", sqmExpression ); final SqmExpressible nodeType = sqmExpression.getNodeType(); if ( nodeType == null ) { // We can't determine the type of the expression @@ -5935,7 +5934,7 @@ else if ( !( inferredMapping instanceof JavaObjectType ) ) { } protected MappingModelExpressible determineValueMapping(SqmParameter sqmParameter) { - log.tracef( "Determining mapping-model type for SqmParameter: %s", sqmParameter ); +// log.tracef( "Determining mapping-model type for SqmParameter: %s", sqmParameter ); final QueryParameterImplementor queryParameter = domainParameterXref.getQueryParameter( sqmParameter ); final QueryParameterBinding binding = domainParameterBindings.getBinding( queryParameter ); final boolean bindingTypeExplicit = binding.getExplicitTemporalPrecision() != null; diff --git a/hibernate-core/src/main/java/org/hibernate/query/sqm/tree/expression/AbstractSqmExpression.java b/hibernate-core/src/main/java/org/hibernate/query/sqm/tree/expression/AbstractSqmExpression.java index 068b5b6e93bc..4377e5c5740d 100644 --- a/hibernate-core/src/main/java/org/hibernate/query/sqm/tree/expression/AbstractSqmExpression.java +++ b/hibernate-core/src/main/java/org/hibernate/query/sqm/tree/expression/AbstractSqmExpression.java @@ -10,7 +10,6 @@ import org.hibernate.query.sqm.NodeBuilder; import org.hibernate.query.sqm.SqmBindableType; -import org.hibernate.query.sqm.SqmTreeCreationLogger; import org.hibernate.query.sqm.internal.SqmCriteriaNodeBuilder; import org.hibernate.query.sqm.tree.jpa.AbstractJpaSelection; import org.hibernate.query.sqm.tree.predicate.SqmPredicate; @@ -41,12 +40,12 @@ public void applyInferableType(@Nullable SqmBindableType type) { } protected void internalApplyInferableType(@Nullable SqmBindableType newType) { - SqmTreeCreationLogger.LOGGER.tracef( - "Applying inferable type to SqmExpression [%s]: %s -> %s", - this, - getExpressible(), - newType - ); +// SqmTreeCreationLogger.LOGGER.tracef( +// "Applying inferable type to SqmExpression [%s]: %s -> %s", +// this, +// getExpressible(), +// newType +// ); setExpressibleType( highestPrecedenceType2( newType, getExpressible() ) ); } diff --git a/hibernate-core/src/main/java/org/hibernate/resource/jdbc/internal/AbstractLogicalConnectionImplementor.java b/hibernate-core/src/main/java/org/hibernate/resource/jdbc/internal/AbstractLogicalConnectionImplementor.java index 13ae57114afe..fae31e7fc7ac 100644 --- a/hibernate-core/src/main/java/org/hibernate/resource/jdbc/internal/AbstractLogicalConnectionImplementor.java +++ b/hibernate-core/src/main/java/org/hibernate/resource/jdbc/internal/AbstractLogicalConnectionImplementor.java @@ -46,18 +46,17 @@ public ResourceRegistry getResourceRegistry() { @Override public void afterStatement() { - log.trace( "LogicalConnection#afterStatement" ); +// log.trace( "LogicalConnection#afterStatement" ); } @Override public void beforeTransactionCompletion() { - log.trace( "LogicalConnection#beforeTransactionCompletion" ); +// log.trace( "LogicalConnection#beforeTransactionCompletion" ); } @Override public void afterTransaction() { - log.trace( "LogicalConnection#afterTransaction" ); - +// log.trace( "LogicalConnection#afterTransaction" ); resourceRegistry.releaseResources(); } diff --git a/hibernate-core/src/main/java/org/hibernate/resource/jdbc/internal/LogicalConnectionManagedImpl.java b/hibernate-core/src/main/java/org/hibernate/resource/jdbc/internal/LogicalConnectionManagedImpl.java index 7bfcf0c40cc0..90c8fcf760c9 100644 --- a/hibernate-core/src/main/java/org/hibernate/resource/jdbc/internal/LogicalConnectionManagedImpl.java +++ b/hibernate-core/src/main/java/org/hibernate/resource/jdbc/internal/LogicalConnectionManagedImpl.java @@ -133,10 +133,10 @@ public void afterStatement() { super.afterStatement(); if ( connectionHandlingMode.getReleaseMode() == AFTER_STATEMENT ) { if ( getResourceRegistry().hasRegisteredResources() ) { - log.trace( "Skipping aggressive release of JDBC Connection after-statement due to held resources" ); + log.trace( "Skipping aggressive JDBC connection release from 'afterStatement' due to held resources" ); } else { - log.trace( "Initiating JDBC connection release from afterStatement" ); + log.trace( "Initiating JDBC connection release from 'afterStatement'" ); releaseConnectionIfNeeded(); } } @@ -146,7 +146,7 @@ public void afterStatement() { public void beforeTransactionCompletion() { super.beforeTransactionCompletion(); if ( connectionHandlingMode.getReleaseMode() == BEFORE_TRANSACTION_COMPLETION ) { - log.trace( "Initiating JDBC connection release from beforeTransactionCompletion" ); + log.trace( "Initiating JDBC connection release from 'beforeTransactionCompletion'" ); releaseConnectionIfNeeded(); } } @@ -159,7 +159,7 @@ public void afterTransaction() { // - AFTER_STATEMENT cases that were circumvented due to held resources // - BEFORE_TRANSACTION_COMPLETION cases that were circumvented because a rollback occurred // (we don't get a beforeTransactionCompletion event on rollback). - log.trace( "Initiating JDBC connection release from afterTransaction" ); + log.trace( "Initiating JDBC connection release from 'afterTransaction'" ); releaseConnectionIfNeeded(); } } diff --git a/hibernate-core/src/main/java/org/hibernate/resource/jdbc/internal/ResourceRegistryStandardImpl.java b/hibernate-core/src/main/java/org/hibernate/resource/jdbc/internal/ResourceRegistryStandardImpl.java index d5bc10b47d5d..02344d3bf559 100644 --- a/hibernate-core/src/main/java/org/hibernate/resource/jdbc/internal/ResourceRegistryStandardImpl.java +++ b/hibernate-core/src/main/java/org/hibernate/resource/jdbc/internal/ResourceRegistryStandardImpl.java @@ -61,7 +61,9 @@ public boolean hasRegisteredResources() { @Override public void register(Statement statement, boolean cancelable) { - if ( IS_TRACE_ENABLED ) log.tracef( "Registering statement [%s]", statement ); + if ( IS_TRACE_ENABLED ) { + log.tracef( "Registering statement [%s]", statement ); + } xref.registerExpectingNew( statement ); @@ -72,7 +74,9 @@ public void register(Statement statement, boolean cancelable) { @Override public void release(Statement statement) { - if ( IS_TRACE_ENABLED ) log.tracev( "Releasing statement [{0}]", statement ); + if ( IS_TRACE_ENABLED ) { + log.tracef( "Releasing statement [%s]", statement ); + } final ResultSetsSet resultSets = xref.remove( statement ); if ( resultSets != null ) { @@ -93,7 +97,9 @@ public void release(Statement statement) { @Override public void release(ResultSet resultSet, Statement statement) { - if ( IS_TRACE_ENABLED ) log.tracef( "Releasing result set [%s]", resultSet ); + if ( IS_TRACE_ENABLED ) { + log.tracef( "Releasing result set [%s]", resultSet ); + } if ( statement == null ) { try { @@ -143,7 +149,9 @@ private static void releaseXref(final Statement s, final ResultSetsSet r) { } private static void close(final ResultSet resultSet) { - if ( IS_TRACE_ENABLED ) log.tracef( "Closing result set [%s]", resultSet ); + if ( IS_TRACE_ENABLED ) { + log.tracef( "Closing result set [%s]", resultSet ); + } try { if ( resultSet != null ) { @@ -160,7 +168,9 @@ private static void close(final ResultSet resultSet) { } private static void close(Statement statement) { - if ( IS_TRACE_ENABLED ) log.tracef( "Closing prepared statement [%s]", statement ); + if ( IS_TRACE_ENABLED ) { + log.tracef( "Closing prepared statement [%s]", statement ); + } try { // if we are unable to "clean" the prepared statement, @@ -194,7 +204,9 @@ private static void close(Statement statement) { @Override public void register(ResultSet resultSet, Statement statement) { - if ( IS_TRACE_ENABLED ) log.tracef( "Registering result set [%s]", resultSet ); + if ( IS_TRACE_ENABLED ) { + log.tracef( "Registering result set [%s]", resultSet ); + } if ( statement == null ) { try { @@ -284,7 +296,7 @@ public void cancelLastQuery() { @Override public void releaseResources() { - if ( IS_TRACE_ENABLED ) log.trace( "Releasing JDBC resources" ); + log.trace( "Releasing JDBC resources" ); if ( jdbcEventHandler != null ) { jdbcEventHandler.jdbcReleaseRegistryResourcesStart(); diff --git a/hibernate-core/src/main/java/org/hibernate/resource/jdbc/spi/JdbcEventHandler.java b/hibernate-core/src/main/java/org/hibernate/resource/jdbc/spi/JdbcEventHandler.java index 7638ea5738aa..30114b79722f 100644 --- a/hibernate-core/src/main/java/org/hibernate/resource/jdbc/spi/JdbcEventHandler.java +++ b/hibernate-core/src/main/java/org/hibernate/resource/jdbc/spi/JdbcEventHandler.java @@ -124,7 +124,6 @@ public void jdbcReleaseRegistryResourcesStart() { if ( jdbcCoordinatorSupplier != null ) { final JdbcCoordinator jdbcCoordinator = jdbcCoordinatorSupplier.get(); if ( jdbcCoordinator != null ) { - log.trace( "Aborting batches as part of ResourceRegistryStandardImpl#releaseResources" ); jdbcCoordinator.abortBatch(); } } diff --git a/hibernate-core/src/main/java/org/hibernate/resource/transaction/backend/jdbc/internal/JdbcResourceLocalTransactionCoordinatorImpl.java b/hibernate-core/src/main/java/org/hibernate/resource/transaction/backend/jdbc/internal/JdbcResourceLocalTransactionCoordinatorImpl.java index ea32816be518..9b9be0d23bac 100644 --- a/hibernate-core/src/main/java/org/hibernate/resource/transaction/backend/jdbc/internal/JdbcResourceLocalTransactionCoordinatorImpl.java +++ b/hibernate-core/src/main/java/org/hibernate/resource/transaction/backend/jdbc/internal/JdbcResourceLocalTransactionCoordinatorImpl.java @@ -151,6 +151,8 @@ private void afterBeginCallback() { // report entering into a "transactional context" transactionCoordinatorOwner.startTransactionBoundary(); + log.trace( "Notifying resource-local transaction observers after begin" ); + // trigger the Transaction-API-only after-begin callback transactionCoordinatorOwner.afterTransactionBegin(); @@ -158,11 +160,10 @@ private void afterBeginCallback() { for ( TransactionObserver observer : observers() ) { observer.afterBegin(); } - log.trace( "ResourceLocalTransactionCoordinatorImpl#afterBeginCallback" ); } private void beforeCompletionCallback() { - log.trace( "ResourceLocalTransactionCoordinatorImpl#beforeCompletionCallback" ); + log.trace( "Notifying resource-local transaction observers before completion" ); try { transactionCoordinatorOwner.beforeTransactionCompletion(); synchronizationRegistry.notifySynchronizationsBeforeTransactionCompletion(); @@ -180,7 +181,7 @@ private void beforeCompletionCallback() { } private void afterCompletionCallback(boolean successful) { - log.tracef( "ResourceLocalTransactionCoordinatorImpl#afterCompletionCallback(%s)", successful ); + log.trace( "Notifying resource-local transaction observers after completion" ); final int statusToSend = successful ? Status.STATUS_COMMITTED : Status.STATUS_ROLLEDBACK; synchronizationRegistry.notifySynchronizationsAfterTransactionCompletion( statusToSend ); transactionCoordinatorOwner.afterTransactionCompletion( successful, false ); diff --git a/hibernate-core/src/main/java/org/hibernate/resource/transaction/backend/jta/internal/JtaTransactionCoordinatorImpl.java b/hibernate-core/src/main/java/org/hibernate/resource/transaction/backend/jta/internal/JtaTransactionCoordinatorImpl.java index bdde96eebca4..e825c8bbb1cf 100644 --- a/hibernate-core/src/main/java/org/hibernate/resource/transaction/backend/jta/internal/JtaTransactionCoordinatorImpl.java +++ b/hibernate-core/src/main/java/org/hibernate/resource/transaction/backend/jta/internal/JtaTransactionCoordinatorImpl.java @@ -325,6 +325,7 @@ public void invalidate() { @Override public void beforeCompletion() { + log.trace( "Notifying JTA transaction observers before completion" ); try { transactionCoordinatorOwner.beforeTransactionCompletion(); } @@ -342,22 +343,22 @@ public void beforeCompletion() { @Override public void afterCompletion(boolean successful, boolean delayed) { - if ( !transactionCoordinatorOwner.isActive() ) { - return; - } + if ( transactionCoordinatorOwner.isActive() ) { + log.trace( "Notifying JTA transaction observers after completion" ); - final int statusToSend = successful ? Status.STATUS_COMMITTED : Status.STATUS_UNKNOWN; - synchronizationRegistry.notifySynchronizationsAfterTransactionCompletion( statusToSend ); + final int statusToSend = successful ? Status.STATUS_COMMITTED : Status.STATUS_UNKNOWN; + synchronizationRegistry.notifySynchronizationsAfterTransactionCompletion( statusToSend ); -// afterCompletionAction.doAction( this, statusToSend ); +// afterCompletionAction.doAction( this, statusToSend ); - transactionCoordinatorOwner.afterTransactionCompletion( successful, delayed ); + transactionCoordinatorOwner.afterTransactionCompletion( successful, delayed ); - for ( TransactionObserver observer : observers() ) { - observer.afterCompletion( successful, delayed ); - } + for ( TransactionObserver observer : observers() ) { + observer.afterCompletion( successful, delayed ); + } - synchronizationRegistered = false; + synchronizationRegistered = false; + } } public void addObserver(TransactionObserver observer) { diff --git a/hibernate-core/src/main/java/org/hibernate/resource/transaction/internal/SynchronizationRegistryStandardImpl.java b/hibernate-core/src/main/java/org/hibernate/resource/transaction/internal/SynchronizationRegistryStandardImpl.java index 12ff3edfcf5f..229c68de0405 100644 --- a/hibernate-core/src/main/java/org/hibernate/resource/transaction/internal/SynchronizationRegistryStandardImpl.java +++ b/hibernate-core/src/main/java/org/hibernate/resource/transaction/internal/SynchronizationRegistryStandardImpl.java @@ -50,8 +50,7 @@ public void registerSynchronization(Synchronization synchronization) { @Override public void notifySynchronizationsBeforeTransactionCompletion() { - log.trace( "SynchronizationRegistryStandardImpl.notifySynchronizationsBeforeTransactionCompletion" ); - + log.trace( "Notifying Synchronizations (before completion)" ); if ( synchronizations != null ) { for ( Synchronization synchronization : synchronizations ) { try { @@ -70,11 +69,7 @@ public void notifySynchronizationsBeforeTransactionCompletion() { @Override public void notifySynchronizationsAfterTransactionCompletion(int status) { - log.tracef( - "SynchronizationRegistryStandardImpl.notifySynchronizationsAfterTransactionCompletion(%s)", - status - ); - + log.tracef( "Notifying Synchronizations (after completion with status %s)", status ); if ( synchronizations != null ) { try { for ( Synchronization synchronization : synchronizations ) { diff --git a/hibernate-core/src/main/java/org/hibernate/service/internal/AbstractServiceRegistryImpl.java b/hibernate-core/src/main/java/org/hibernate/service/internal/AbstractServiceRegistryImpl.java index a3f0a80264ac..a6d0451edb9b 100644 --- a/hibernate-core/src/main/java/org/hibernate/service/internal/AbstractServiceRegistryImpl.java +++ b/hibernate-core/src/main/java/org/hibernate/service/internal/AbstractServiceRegistryImpl.java @@ -407,11 +407,11 @@ public synchronized void deRegisterChild(ServiceRegistryImplementor child) { childRegistries.remove( child ); if ( childRegistries.isEmpty() ) { if ( autoCloseRegistry ) { - log.trace( "Implicitly destroying ServiceRegistry on deregistration of all child ServiceRegistries" ); + log.trace( "Automatically destroying ServiceRegistry after deregistration of every child ServiceRegistry" ); destroy(); } else { - log.trace( "Skipping implicitly destroying ServiceRegistry on deregistration of all child ServiceRegistries" ); + log.trace( "Skipping destroying ServiceRegistry after deregistration of every child ServiceRegistru" ); } } } diff --git a/hibernate-core/src/main/java/org/hibernate/service/internal/SessionFactoryServiceRegistryImpl.java b/hibernate-core/src/main/java/org/hibernate/service/internal/SessionFactoryServiceRegistryImpl.java index 8164ed2bd762..2ccd7535f3c1 100644 --- a/hibernate-core/src/main/java/org/hibernate/service/internal/SessionFactoryServiceRegistryImpl.java +++ b/hibernate-core/src/main/java/org/hibernate/service/internal/SessionFactoryServiceRegistryImpl.java @@ -101,8 +101,8 @@ public ServiceRegistryImplementor getServiceRegistry() { public @Nullable R getService(Class serviceRole) { if ( serviceRole.equals( EventListenerRegistry.class ) ) { log.debug( - "EventListenerRegistry access via ServiceRegistry is deprecated. " - + "Use 'sessionFactory.getEventEngine().getListenerRegistry()' instead" + "EventListenerRegistry access via ServiceRegistry is deprecated - " + + "use 'sessionFactory.getEventEngine().getListenerRegistry()' instead" ); //noinspection unchecked diff --git a/hibernate-core/src/main/java/org/hibernate/sql/ast/SqlTreePrinter.java b/hibernate-core/src/main/java/org/hibernate/sql/ast/SqlTreePrinter.java index 3a06e0ca7dd6..14c7606d6ad3 100644 --- a/hibernate-core/src/main/java/org/hibernate/sql/ast/SqlTreePrinter.java +++ b/hibernate-core/src/main/java/org/hibernate/sql/ast/SqlTreePrinter.java @@ -15,6 +15,7 @@ import org.hibernate.sql.ast.tree.from.QueryPartTableReference; import org.hibernate.sql.ast.tree.from.TableGroup; import org.hibernate.sql.ast.tree.from.TableGroupJoin; +import org.hibernate.sql.ast.tree.from.TableReference; import org.hibernate.sql.ast.tree.from.TableReferenceJoin; import org.hibernate.sql.ast.tree.from.ValuesTableReference; import org.hibernate.sql.ast.tree.insert.InsertSelectStatement; @@ -125,7 +126,7 @@ private void visitTableGroup(TableGroup tableGroup) { private String toDisplayText(TableGroup tableGroup) { return tableGroup.getClass().getSimpleName() + " (" - + tableGroup.getGroupAlias() + " : " + + tableGroup.getGroupAlias() + ": " + tableGroup.getNavigablePath() + ")"; } @@ -134,36 +135,35 @@ private void logTableGroupDetails(TableGroup tableGroup) { if ( !tableGroup.isInitialized() ) { return; } - if ( tableGroup.getPrimaryTableReference() instanceof NamedTableReference ) { + final TableReference primaryTableReference = tableGroup.getPrimaryTableReference(); + if ( primaryTableReference instanceof NamedTableReference ) { logWithIndentation( - "primaryTableReference : %s as %s", + "primaryTableReference: %s as %s", tableGroup.getPrimaryTableReference().getTableId(), tableGroup.getPrimaryTableReference().getIdentificationVariable() ); } + else if ( primaryTableReference instanceof ValuesTableReference ) { + logWithIndentation( + "primaryTableReference: values (..) as %s", + primaryTableReference.getIdentificationVariable() + ); + } + else if ( primaryTableReference instanceof FunctionTableReference ) { + logWithIndentation( + "primaryTableReference: %s(...) as %s", + ((FunctionTableReference) primaryTableReference).getFunctionExpression().getFunctionName(), + primaryTableReference.getIdentificationVariable() + ); + } else { - if ( tableGroup.getPrimaryTableReference() instanceof ValuesTableReference ) { - logWithIndentation( - "primaryTableReference : values (..) as %s", - tableGroup.getPrimaryTableReference().getIdentificationVariable() - ); - } - else if ( tableGroup.getPrimaryTableReference() instanceof FunctionTableReference ) { - logWithIndentation( - "primaryTableReference : %s(...) as %s", - ( (FunctionTableReference) tableGroup.getPrimaryTableReference() ).getFunctionExpression().getFunctionName(), - tableGroup.getPrimaryTableReference().getIdentificationVariable() - ); - } - else { - logNode( - "PrimaryTableReference as " + tableGroup.getPrimaryTableReference().getIdentificationVariable(), - () -> { - Statement statement = ( (QueryPartTableReference) tableGroup.getPrimaryTableReference() ).getStatement(); - visitStatement( statement ); - } - ); - } + logNode( + "PrimaryTableReference as " + primaryTableReference.getIdentificationVariable(), + () -> { + Statement statement = ((QueryPartTableReference) primaryTableReference).getStatement(); + visitStatement( statement ); + } + ); } final List tableReferenceJoins = tableGroup.getTableReferenceJoins(); @@ -202,7 +202,8 @@ else if ( tableGroup.getPrimaryTableReference() instanceof FunctionTableReferenc private void visitTableGroupJoin(TableGroupJoin tableGroupJoin) { logNode( - tableGroupJoin.getJoinType().getText() + " join " + toDisplayText( tableGroupJoin.getJoinedGroup() ), + tableGroupJoin.getJoinType().getText() + "join " + + toDisplayText( tableGroupJoin.getJoinedGroup() ), () -> logTableGroupDetails( tableGroupJoin.getJoinedGroup() ) ); } diff --git a/hibernate-core/src/main/java/org/hibernate/sql/ast/spi/SimpleFromClauseAccessImpl.java b/hibernate-core/src/main/java/org/hibernate/sql/ast/spi/SimpleFromClauseAccessImpl.java index 669a1022ec74..eb2fb98b955c 100644 --- a/hibernate-core/src/main/java/org/hibernate/sql/ast/spi/SimpleFromClauseAccessImpl.java +++ b/hibernate-core/src/main/java/org/hibernate/sql/ast/spi/SimpleFromClauseAccessImpl.java @@ -11,12 +11,10 @@ import org.hibernate.metamodel.model.domain.NavigableRole; import org.hibernate.spi.NavigablePath; import org.hibernate.sql.ast.SqlAstJoinType; -import org.hibernate.sql.ast.SqlTreeCreationLogger; import org.hibernate.sql.ast.tree.from.CorrelatedTableGroup; import org.hibernate.sql.ast.tree.from.TableGroup; import org.hibernate.sql.ast.tree.from.TableGroupJoin; -import org.jboss.logging.Logger; import org.checkerframework.checker.nullness.qual.Nullable; @@ -115,24 +113,25 @@ private TableGroup getCorrelatedTableGroup(TableGroup tableGroup) { @Override public void registerTableGroup(NavigablePath navigablePath, TableGroup tableGroup) { - final Logger logger = SqlTreeCreationLogger.LOGGER; - final boolean traceEnabled = logger.isTraceEnabled(); - if ( traceEnabled ) { - logger.tracef( - "Registration of TableGroup [%s] with identifierForTableGroup [%s] for NavigablePath [%s] ", - tableGroup, - tableGroup.getNavigablePath().getIdentifierForTableGroup(), - navigablePath.getIdentifierForTableGroup() - ); - } + // Logging disabled here because too verbose +// final Logger logger = SqlTreeCreationLogger.LOGGER; +// final boolean traceEnabled = logger.isTraceEnabled(); +// if ( traceEnabled ) { +// logger.tracef( +// "Registration of TableGroup [%s] with identifier [%s] for NavigablePath [%s] ", +// tableGroup, +// tableGroup.getNavigablePath().getIdentifierForTableGroup(), +// navigablePath.getIdentifierForTableGroup() +// ); +// } final TableGroup previous = tableGroupMap.put( navigablePath, tableGroup ); - if ( traceEnabled && previous != null ) { - logger.tracef( - "Registration of TableGroup [%s] for NavigablePath [%s] overrode previous registration: %s", - tableGroup, - navigablePath, - previous - ); - } +// if ( traceEnabled && previous != null ) { +// logger.tracef( +// "Registration of TableGroup [%s] for NavigablePath [%s] overrode previous registration: %s", +// tableGroup, +// navigablePath, +// previous +// ); +// } } } diff --git a/hibernate-core/src/main/java/org/hibernate/sql/ast/spi/SqlAliasBaseImpl.java b/hibernate-core/src/main/java/org/hibernate/sql/ast/spi/SqlAliasBaseImpl.java index 6f4e93afd567..0de051bf9493 100644 --- a/hibernate-core/src/main/java/org/hibernate/sql/ast/spi/SqlAliasBaseImpl.java +++ b/hibernate-core/src/main/java/org/hibernate/sql/ast/spi/SqlAliasBaseImpl.java @@ -4,7 +4,6 @@ */ package org.hibernate.sql.ast.spi; -import org.hibernate.sql.ast.SqlTreeCreationLogger; /** * Standard SqlAliasBase impl @@ -27,7 +26,7 @@ public String getAliasStem() { @Override public String generateNewAlias() { final String alias = stem + "_" + ( aliasCount++ ); - SqlTreeCreationLogger.LOGGER.tracef( "Created new SQL alias: %s", alias ); +// SqlTreeCreationLogger.LOGGER.tracef( "Created new SQL alias: %s", alias ); return alias; } diff --git a/hibernate-core/src/main/java/org/hibernate/sql/ast/tree/from/DerivedTableReference.java b/hibernate-core/src/main/java/org/hibernate/sql/ast/tree/from/DerivedTableReference.java index 3c0d27958f16..ff32f703891d 100644 --- a/hibernate-core/src/main/java/org/hibernate/sql/ast/tree/from/DerivedTableReference.java +++ b/hibernate-core/src/main/java/org/hibernate/sql/ast/tree/from/DerivedTableReference.java @@ -47,7 +47,7 @@ public TableReference resolveTableReference( String tableExpression) { throw new UnknownTableReferenceException( tableExpression, - "TableReferences cannot be resolved relative to DerivedTableReferences - `" + tableExpression + "` : " + navigablePath + "TableReferences cannot be resolved relative to DerivedTableReferences - '" + tableExpression + "' : " + navigablePath ); } @@ -58,7 +58,7 @@ public TableReference resolveTableReference( String tableExpression) { throw new UnknownTableReferenceException( tableExpression, - "TableReferences cannot be resolved relative to DerivedTableReferences - `" + tableExpression + "` : " + navigablePath + "TableReferences cannot be resolved relative to DerivedTableReferences - '" + tableExpression + "' : " + navigablePath ); } diff --git a/hibernate-core/src/main/java/org/hibernate/sql/ast/tree/from/TableGroupJoin.java b/hibernate-core/src/main/java/org/hibernate/sql/ast/tree/from/TableGroupJoin.java index 8275e92e28b3..0f773ea06052 100644 --- a/hibernate-core/src/main/java/org/hibernate/sql/ast/tree/from/TableGroupJoin.java +++ b/hibernate-core/src/main/java/org/hibernate/sql/ast/tree/from/TableGroupJoin.java @@ -8,7 +8,6 @@ import org.hibernate.query.sqm.sql.internal.DomainResultProducer; import org.hibernate.sql.ast.SqlAstJoinType; import org.hibernate.sql.ast.SqlAstWalker; -import org.hibernate.sql.ast.SqlTreeCreationLogger; import org.hibernate.sql.ast.spi.SqlAstTreeHelper; import org.hibernate.sql.ast.tree.SqlAstNode; import org.hibernate.sql.ast.tree.predicate.Predicate; @@ -54,12 +53,12 @@ public SqlAstJoinType getJoinType() { } public void setJoinType(SqlAstJoinType joinType) { - SqlTreeCreationLogger.LOGGER.tracef( - "Adjusting join-type for TableGroupJoin(%s) : %s -> %s", - navigablePath, - this.joinType, - joinType - ); +// SqlTreeCreationLogger.LOGGER.tracef( +// "Adjusting join-type for TableGroupJoin(%s) : %s -> %s", +// navigablePath, +// this.joinType, +// joinType +// ); this.joinType = joinType; } diff --git a/hibernate-core/src/main/java/org/hibernate/sql/exec/internal/JdbcSelectExecutorStandardImpl.java b/hibernate-core/src/main/java/org/hibernate/sql/exec/internal/JdbcSelectExecutorStandardImpl.java index f4b79cfecb4a..3c7e7a0fbc9b 100644 --- a/hibernate-core/src/main/java/org/hibernate/sql/exec/internal/JdbcSelectExecutorStandardImpl.java +++ b/hibernate-core/src/main/java/org/hibernate/sql/exec/internal/JdbcSelectExecutorStandardImpl.java @@ -319,8 +319,8 @@ private JdbcValues resolveJdbcValuesSource( } } else { - SQL_EXEC_LOGGER.tracef( "Skipping reading Query result cache data: cache-enabled = %s, cache-mode = %s", - queryCacheEnabled, + SQL_EXEC_LOGGER.tracef( "Skipping reading query result cache data (query cache %s, cache mode %s)", + queryCacheEnabled ? "enabled" : "disabled", cacheMode.name() ); cachedResults = null; diff --git a/hibernate-core/src/main/java/org/hibernate/sql/model/ast/builder/AbstractTableMutationBuilder.java b/hibernate-core/src/main/java/org/hibernate/sql/model/ast/builder/AbstractTableMutationBuilder.java index 2eed3305950e..74b45f7a0471 100644 --- a/hibernate-core/src/main/java/org/hibernate/sql/model/ast/builder/AbstractTableMutationBuilder.java +++ b/hibernate-core/src/main/java/org/hibernate/sql/model/ast/builder/AbstractTableMutationBuilder.java @@ -135,6 +135,6 @@ protected final List combine(List list1, List... additionalLists) { @Override public String toString() { - return "TableMutationBuilder( " + mutationType + " - `" + mutatingTable.getTableName() + "`)"; + return "TableMutationBuilder( " + mutationType + " - '" + mutatingTable.getTableName() + "')"; } } diff --git a/hibernate-core/src/main/java/org/hibernate/sql/model/jdbc/DeleteOrUpsertOperation.java b/hibernate-core/src/main/java/org/hibernate/sql/model/jdbc/DeleteOrUpsertOperation.java index a17a7d8a561c..1a3ea8a308dc 100644 --- a/hibernate-core/src/main/java/org/hibernate/sql/model/jdbc/DeleteOrUpsertOperation.java +++ b/hibernate-core/src/main/java/org/hibernate/sql/model/jdbc/DeleteOrUpsertOperation.java @@ -101,7 +101,7 @@ public void performMutation( } private void performDelete(JdbcValueBindings jdbcValueBindings, SharedSessionContractImplementor session) { - MODEL_MUTATION_LOGGER.tracef( "#performDelete(%s)", tableMapping.getTableName() ); + MODEL_MUTATION_LOGGER.tracef( "Performing delete (%s)", tableMapping.getTableName() ); final TableDeleteStandard upsertDeleteAst = new TableDeleteStandard( optionalTableUpdate.getMutatingTable(), @@ -125,7 +125,7 @@ private void performDelete(JdbcValueBindings jdbcValueBindings, SharedSessionCon bindDeleteKeyValues( jdbcValueBindings, statementDetails, session ); final int rowCount = session.getJdbcCoordinator().getResultSetReturn() .executeUpdate( upsertDeleteStatement, statementDetails.getSqlString() ); - MODEL_MUTATION_LOGGER.tracef( "`%s` rows upsert-deleted from `%s`", rowCount, tableMapping.getTableName() ); + MODEL_MUTATION_LOGGER.tracef( "%s rows upsert-deleted from '%s'", rowCount, tableMapping.getTableName() ); try { getExpectation().verifyOutcome( rowCount, upsertDeleteStatement, -1, statementDetails.getSqlString() ); } @@ -189,7 +189,7 @@ private static void bindKeyValue( } private void performUpsert(JdbcValueBindings jdbcValueBindings, SharedSessionContractImplementor session) { - MODEL_MUTATION_LOGGER.tracef( "#performUpsert(%s)", tableMapping.getTableName() ); + MODEL_MUTATION_LOGGER.tracef( "Performing upsert (%s)", tableMapping.getTableName() ); final var statementGroup = new PreparedStatementGroupSingleTable( upsertOperation, session ); final var statementDetails = statementGroup.resolvePreparedStatementDetails( tableMapping.getTableName() ); @@ -201,7 +201,7 @@ private void performUpsert(JdbcValueBindings jdbcValueBindings, SharedSessionCon final int rowCount = session.getJdbcCoordinator().getResultSetReturn() .executeUpdate( updateStatement, statementDetails.getSqlString() ); - MODEL_MUTATION_LOGGER.tracef( "`%s` rows upserted into `%s`", rowCount, tableMapping.getTableName() ); + MODEL_MUTATION_LOGGER.tracef( "%s rows upserted in '%s'", rowCount, tableMapping.getTableName() ); try { getExpectation().verifyOutcome( rowCount, updateStatement, -1, statementDetails.getSqlString() ); } diff --git a/hibernate-core/src/main/java/org/hibernate/sql/model/jdbc/OptionalTableUpdateOperation.java b/hibernate-core/src/main/java/org/hibernate/sql/model/jdbc/OptionalTableUpdateOperation.java index 7f017213c141..37bde22e7902 100644 --- a/hibernate-core/src/main/java/org/hibernate/sql/model/jdbc/OptionalTableUpdateOperation.java +++ b/hibernate-core/src/main/java/org/hibernate/sql/model/jdbc/OptionalTableUpdateOperation.java @@ -149,7 +149,7 @@ public void performMutation( if ( !wasUpdated ) { MODEL_MUTATION_LOGGER.tracef( - "Upsert update altered no rows - inserting: %s", + "Upsert update altered no rows; performing insert (%s)", tableMapping.getTableName() ); try { @@ -300,7 +300,7 @@ protected JdbcDeleteMutation createJdbcDelete(SharedSessionContractImplementor s private boolean performUpdate( JdbcValueBindings jdbcValueBindings, SharedSessionContractImplementor session) { - MODEL_MUTATION_LOGGER.tracef( "#performUpdate(%s)", tableMapping.getTableName() ); + MODEL_MUTATION_LOGGER.tracef( "Performing update (%s)", tableMapping.getTableName() ); final JdbcServices jdbcServices = session.getJdbcServices(); final var statementGroup = new PreparedStatementGroupSingleTable( createJdbcUpdate( session ), session ); diff --git a/hibernate-core/src/main/java/org/hibernate/sql/results/graph/embeddable/internal/EmbeddableInitializerImpl.java b/hibernate-core/src/main/java/org/hibernate/sql/results/graph/embeddable/internal/EmbeddableInitializerImpl.java index 7265a086636b..d76e9ac85f27 100644 --- a/hibernate-core/src/main/java/org/hibernate/sql/results/graph/embeddable/internal/EmbeddableInitializerImpl.java +++ b/hibernate-core/src/main/java/org/hibernate/sql/results/graph/embeddable/internal/EmbeddableInitializerImpl.java @@ -41,7 +41,6 @@ import org.checkerframework.checker.nullness.qual.Nullable; -import static org.hibernate.sql.results.graph.embeddable.EmbeddableLoadingLogger.EMBEDDED_LOAD_LOGGER; import static org.hibernate.sql.results.graph.entity.internal.BatchEntityInsideEmbeddableSelectFetchInitializer.BATCH_PROPERTY; /** @@ -469,7 +468,7 @@ private void prepareCompositeInstance(EmbeddableInitializerData data) { data.setInstance( createCompositeInstance( data ) ); } - EMBEDDED_LOAD_LOGGER.tracef( "Created composite instance [%s]", navigablePath ); +// EMBEDDED_LOAD_LOGGER.tracef( "Created composite instance [%s]", navigablePath ); } private void extractRowState(EmbeddableInitializerData data) { @@ -519,7 +518,7 @@ private Object createCompositeInstance(EmbeddableInitializerData data) { : data.concreteEmbeddableType.getInstantiator(); final Object instance = instantiator.instantiate( data ); data.setState( State.RESOLVED ); - EMBEDDED_LOAD_LOGGER.tracef( "Created composite instance [%s]: %s", navigablePath, instance ); +// EMBEDDED_LOAD_LOGGER.tracef( "Created composite instance [%s]: %s", navigablePath, instance ); return instance; } @@ -576,6 +575,7 @@ private Object determineParentInstance(Initializer parentInitializer, RowProc @Override public String toString() { - return getClass().getSimpleName() + "(" + navigablePath + ") : `" + getInitializedPart().getJavaType().getJavaTypeClass() + "`"; + return getClass().getSimpleName() + "(" + navigablePath + ") : " + + getInitializedPart().getJavaType().getJavaTypeClass().getSimpleName(); } } diff --git a/hibernate-core/src/main/java/org/hibernate/sql/results/internal/NavigablePathMapToInitializer.java b/hibernate-core/src/main/java/org/hibernate/sql/results/internal/NavigablePathMapToInitializer.java index 6d0f4d975e48..5b417a9f4b72 100644 --- a/hibernate-core/src/main/java/org/hibernate/sql/results/internal/NavigablePathMapToInitializer.java +++ b/hibernate-core/src/main/java/org/hibernate/sql/results/internal/NavigablePathMapToInitializer.java @@ -8,7 +8,6 @@ import java.util.Objects; import org.hibernate.spi.NavigablePath; -import org.hibernate.sql.results.ResultsLogger; import org.hibernate.sql.results.graph.Initializer; @@ -47,32 +46,34 @@ public void put(final NavigablePath navigablePath, final Initializer initiali } public void logInitializers() { - final ResultsLogger logger = ResultsLogger.RESULTS_MESSAGE_LOGGER; - if ( logger.isTraceEnabled() ) { - if ( map == null ) { - logger.trace( "Initializer list is empty" ); - } - else { - //Apparently we want to log this on multiple lines (existing code did this - not sure if that was by design): - //using a StringBuilder to avoid potentially interleaving the logs from different operations. - final StringBuilder sb = new StringBuilder( "Initializer list:\n" ); - for ( var holderEntry : map.entrySet() ) { - final NavigablePath navigablePath = holderEntry.getKey(); - final Initializer initializer = holderEntry.getValue().initializer; - final String formatted = String.format( - " %s -> %s@%s (%s)", - navigablePath, - initializer, - initializer.hashCode(), - initializer.getInitializedPart() - ); - sb.append( '\t' ); - sb.append( formatted ); - sb.append( '\n' ); - } - logger.trace( sb.toString() ); - } - } + // Disabling for now because way too verbose and messy, and + // because it duplicates the 'Registering initializer' logs +// final ResultsLogger logger = ResultsLogger.RESULTS_MESSAGE_LOGGER; +// if ( logger.isTraceEnabled() ) { +// if ( map == null ) { +// logger.trace( "Initializer list is empty" ); +// } +// else { +// //Apparently we want to log this on multiple lines (existing code did this - not sure if that was by design): +// //using a StringBuilder to avoid potentially interleaving the logs from different operations. +// final StringBuilder sb = new StringBuilder( "Initializer list:\n" ); +// for ( var holderEntry : map.entrySet() ) { +// final NavigablePath navigablePath = holderEntry.getKey(); +// final Initializer initializer = holderEntry.getValue().initializer; +// final String formatted = String.format( +// " %s -> %s [@%s] %s", +// navigablePath, +// initializer, +// initializer.hashCode(), +// initializer.getInitializedPart() +// ); +// sb.append( '\t' ); +// sb.append( formatted ); +// sb.append( '\n' ); +// } +// logger.trace( sb.toString() ); +// } +// } } //Custom holder to avoid type pollution: diff --git a/hibernate-core/src/main/java/org/hibernate/sql/results/jdbc/internal/StandardJdbcValuesMapping.java b/hibernate-core/src/main/java/org/hibernate/sql/results/jdbc/internal/StandardJdbcValuesMapping.java index e587fa0d38b1..e83c28974af9 100644 --- a/hibernate-core/src/main/java/org/hibernate/sql/results/jdbc/internal/StandardJdbcValuesMapping.java +++ b/hibernate-core/src/main/java/org/hibernate/sql/results/jdbc/internal/StandardJdbcValuesMapping.java @@ -10,13 +10,10 @@ import org.hibernate.LockMode; import org.hibernate.engine.spi.SessionFactoryImplementor; -import org.hibernate.internal.util.collections.ArrayHelper; -import org.hibernate.internal.util.collections.CollectionHelper; import org.hibernate.metamodel.mapping.ModelPart; import org.hibernate.spi.NavigablePath; import org.hibernate.sql.ast.spi.SqlAstCreationContext; import org.hibernate.sql.ast.spi.SqlSelection; -import org.hibernate.sql.results.ResultsLogger; import org.hibernate.sql.results.graph.AssemblerCreationState; import org.hibernate.sql.results.graph.DomainResult; import org.hibernate.sql.results.graph.DomainResultAssembler; @@ -32,6 +29,10 @@ import org.hibernate.sql.results.jdbc.spi.JdbcValuesMapping; import org.hibernate.sql.results.jdbc.spi.JdbcValuesMappingResolution; +import static org.hibernate.internal.util.collections.ArrayHelper.EMPTY_INT_ARRAY; +import static org.hibernate.internal.util.collections.CollectionHelper.arrayList; +import static org.hibernate.sql.results.ResultsLogger.RESULTS_MESSAGE_LOGGER; + /** * @author Steve Ebersole */ @@ -74,7 +75,7 @@ public StandardJdbcValuesMapping( } this.needsResolve = needsResolve; - this.valueIndexesToCacheIndexes = cacheIndex == 0 ? ArrayHelper.EMPTY_INT_ARRAY : valueIndexesToCacheIndexes; + this.valueIndexesToCacheIndexes = cacheIndex == 0 ? EMPTY_INT_ARRAY : valueIndexesToCacheIndexes; this.rowToCacheSize = cacheIndex; } @@ -109,37 +110,34 @@ public boolean needsResolve() { @Override public JdbcValuesMappingResolution resolveAssemblers(SessionFactoryImplementor sessionFactory) { - final JdbcValuesMappingResolutionImpl resolution = this.resolution; if ( resolution != null ) { return resolution; } - final AssemblerCreationStateImpl creationState = new AssemblerCreationStateImpl( - this, - sessionFactory.getSqlTranslationEngine() - ); - - DomainResultAssembler[] domainResultAssemblers = - resolveAssemblers( creationState ).toArray(new DomainResultAssembler[0]); - creationState.initializerMap.logInitializers(); - return this.resolution = new JdbcValuesMappingResolutionImpl( - domainResultAssemblers, - creationState.hasCollectionInitializers, - creationState.initializerListBuilder.build() - ); + else { + final AssemblerCreationStateImpl creationState = + new AssemblerCreationStateImpl( this, + sessionFactory.getSqlTranslationEngine() ); + final var domainResultAssemblers = resolveAssemblers( creationState ); + creationState.initializerMap.logInitializers(); + resolution = new JdbcValuesMappingResolutionImpl( + domainResultAssemblers, + creationState.hasCollectionInitializers, + creationState.initializerListBuilder.build() + ); + return resolution; + } } - private List> resolveAssemblers(AssemblerCreationState creationState) { - final List> assemblers = CollectionHelper.arrayList( domainResults.size() ); - - //noinspection ForLoopReplaceableByForEach - for ( int i = 0; i < domainResults.size(); i++ ) { - final DomainResultAssembler resultAssembler = domainResults.get( i ) - .createResultAssembler( null, creationState ); - + private DomainResultAssembler[] resolveAssemblers(AssemblerCreationState creationState) { + final int size = domainResults.size(); + final List> assemblers = arrayList( size ); + for ( int i = 0; i < size; i++ ) { + final DomainResultAssembler resultAssembler = + domainResults.get( i ) + .createResultAssembler( null, creationState ); assemblers.add( resultAssembler ); } - - return assemblers; + return assemblers.toArray( new DomainResultAssembler[0] ); } @Override @@ -232,19 +230,13 @@ public Initializer resolveInitializer( if ( existing != null ) { if ( fetchedModelPart.getNavigableRole().equals( existing.getInitializedPart().getNavigableRole() ) ) { - ResultsLogger.RESULTS_MESSAGE_LOGGER.tracef( - "Returning previously-registered initializer : %s", - existing - ); + RESULTS_MESSAGE_LOGGER.tracef( "Returning previously-registered initializer: %s", existing ); return existing; } } final Initializer initializer = producer.createInitializer( resultGraphNode, parent, this ); - ResultsLogger.RESULTS_MESSAGE_LOGGER.tracef( - "Registering initializer : %s", - initializer - ); + RESULTS_MESSAGE_LOGGER.tracef( "Registering initializer: %s", initializer ); if ( initializer instanceof AbstractImmediateCollectionInitializer ) { hasCollectionInitializers = true; @@ -259,6 +251,5 @@ public Initializer resolveInitializer( public SqlAstCreationContext getSqlAstCreationContext() { return sqlAstCreationContexty; } - } } diff --git a/hibernate-core/src/main/java/org/hibernate/tool/schema/spi/SchemaManagementToolCoordinator.java b/hibernate-core/src/main/java/org/hibernate/tool/schema/spi/SchemaManagementToolCoordinator.java index c415099d5188..a12438177e18 100644 --- a/hibernate-core/src/main/java/org/hibernate/tool/schema/spi/SchemaManagementToolCoordinator.java +++ b/hibernate-core/src/main/java/org/hibernate/tool/schema/spi/SchemaManagementToolCoordinator.java @@ -68,7 +68,7 @@ public static void process( if ( groupings.isEmpty() ) { // no actions specified - log.debug( "No actions found; doing nothing" ); + log.debug( "No schema management actions found" ); return; } @@ -751,7 +751,7 @@ public static Set interpret(Set contributors, Map c } if ( databaseActionToUse == Action.NONE && scriptActionToUse == Action.NONE ) { - log.debugf( "No schema actions specified for contributor `%s`; doing nothing", contributor ); + log.debugf( "No schema actions specified for contributor '%s'", contributor ); continue; } diff --git a/hibernate-core/src/main/java/org/hibernate/type/spi/TypeConfiguration.java b/hibernate-core/src/main/java/org/hibernate/type/spi/TypeConfiguration.java index 56681c4f79ce..ffc7a11c6498 100644 --- a/hibernate-core/src/main/java/org/hibernate/type/spi/TypeConfiguration.java +++ b/hibernate-core/src/main/java/org/hibernate/type/spi/TypeConfiguration.java @@ -46,7 +46,6 @@ import org.hibernate.dialect.Dialect; import org.hibernate.engine.spi.SessionFactoryImplementor; import org.hibernate.id.uuid.LocalObjectUuidHelper; -import org.hibernate.internal.CoreMessageLogger; import org.hibernate.internal.SessionFactoryRegistry; import org.hibernate.jpa.spi.JpaCompliance; import org.hibernate.metamodel.mapping.BasicValuedMapping; @@ -82,7 +81,6 @@ import jakarta.persistence.TemporalType; -import static org.hibernate.internal.CoreLogging.messageLogger; import static org.hibernate.query.sqm.internal.TypecheckUtil.isNumberArray; /** @@ -115,7 +113,7 @@ */ @Incubating public class TypeConfiguration implements SessionFactoryObserver, Serializable { - private static final CoreMessageLogger log = messageLogger( Scope.class ); +// private static final CoreMessageLogger log = messageLogger( Scope.class ); private final String uuid = LocalObjectUuidHelper.generateLocalObjectUuid(); @@ -194,7 +192,7 @@ public MetadataBuildingContext getMetadataBuildingContext() { * @param metadataBuildingContext a {@link MetadataBuildingContext} */ public void scope(MetadataBuildingContext metadataBuildingContext) { - log.tracef( "Scoping TypeConfiguration [%s] to MetadataBuildingContext [%s]", this, metadataBuildingContext ); +// log.tracef( "Scoping TypeConfiguration [%s] to MetadataBuildingContext [%s]", this, metadataBuildingContext ); scope.setMetadataBuildingContext( metadataBuildingContext ); } @@ -206,7 +204,7 @@ public void scope(MetadataBuildingContext metadataBuildingContext) { * @param sessionFactory a {@link SessionFactory} that is in a very fragile state */ public void scope(SessionFactoryImplementor sessionFactory) { - log.tracef( "Scoping TypeConfiguration [%s] to SessionFactoryImplementor [%s]", this, sessionFactory ); +// log.tracef( "Scoping TypeConfiguration [%s] to SessionFactoryImplementor [%s]", this, sessionFactory ); if ( scope.getMetadataBuildingContext() == null ) { throw new IllegalStateException( "MetadataBuildingContext not known" ); @@ -273,13 +271,13 @@ public void sessionFactoryCreated(SessionFactory factory) { // Instead of allowing scope#setSessionFactory to influence this, we use the SessionFactoryObserver callback // to handle this, allowing any SessionFactory constructor code to be able to continue to have access to the // MetadataBuildingContext through TypeConfiguration until this callback is fired. - log.tracef( "Handling #sessionFactoryCreated from [%s] for TypeConfiguration", factory ); +// log.tracef( "Handling #sessionFactoryCreated from [%s] for TypeConfiguration", factory ); scope.setMetadataBuildingContext( null ); } @Override public void sessionFactoryClosed(SessionFactory factory) { - log.tracef( "Handling #sessionFactoryClosed from [%s] for TypeConfiguration", factory ); +// log.tracef( "Handling #sessionFactoryClosed from [%s] for TypeConfiguration", factory ); scope.unsetSessionFactory( factory ); // todo (6.0) : finish this // release Database, descriptor Maps, etc... things that are only @@ -582,7 +580,9 @@ private SessionFactoryImplementor getSessionFactory() { */ private void setSessionFactory(SessionFactoryImplementor factory) { if ( sessionFactory != null ) { - log.scopingTypesToSessionFactoryAfterAlreadyScoped( sessionFactory, factory ); +// log.scopingTypesToSessionFactoryAfterAlreadyScoped( sessionFactory, factory ); + throw new IllegalStateException( "TypeConfiguration was already scoped to SessionFactory: " + + sessionFactory.getUuid() ); } else { sessionFactoryUuid = factory.getUuid(); @@ -605,7 +605,7 @@ private static String getFactoryName(SessionFactoryImplementor factory) { } private void unsetSessionFactory(SessionFactory factory) { - log.tracef( "Un-scoping TypeConfiguration [%s] from SessionFactory [%s]", this, factory ); +// log.tracef( "Un-scoping TypeConfiguration [%s] from SessionFactory [%s]", this, factory ); sessionFactory = null; } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/resource/transaction/TransactionTimeoutTests.java b/hibernate-core/src/test/java/org/hibernate/orm/test/resource/transaction/TransactionTimeoutTests.java index 9ca7ed5809dc..363d648d8e6f 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/resource/transaction/TransactionTimeoutTests.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/resource/transaction/TransactionTimeoutTests.java @@ -50,7 +50,7 @@ void testJdbcTxn(SessionFactoryScope sessions) { } catch (PersistenceException e) { assertThat( e ).isInstanceOf( TransactionException.class ); - assertThat( e ).hasMessageContaining( "transaction timeout expired" ); + assertThat( e ).hasMessageContaining( "Transaction timeout expired" ); } } ); } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/softdelete/CustomTrueFalseConverter.java b/hibernate-core/src/test/java/org/hibernate/orm/test/softdelete/CustomTrueFalseConverter.java index 0a33bcd176f9..b659db0c2bc9 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/softdelete/CustomTrueFalseConverter.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/softdelete/CustomTrueFalseConverter.java @@ -32,6 +32,6 @@ public Boolean convertToEntityAttribute(Character dbData) { if ( dbData.equals( 'F' ) ) { return false; } - throw new IllegalArgumentException( "Unexpected database value - `" + dbData + "`, expected 'T' or 'F'" ); + throw new IllegalArgumentException( "Unexpected database value - '" + dbData + "', expected 'T' or 'F'" ); } } diff --git a/hibernate-testing/src/main/java/org/hibernate/testing/transaction/TransactionUtil2.java b/hibernate-testing/src/main/java/org/hibernate/testing/transaction/TransactionUtil2.java index 25d9f8e15ef0..0501476d845d 100644 --- a/hibernate-testing/src/main/java/org/hibernate/testing/transaction/TransactionUtil2.java +++ b/hibernate-testing/src/main/java/org/hibernate/testing/transaction/TransactionUtil2.java @@ -39,7 +39,7 @@ public static void inSession(SessionFactoryImplementor sfi, Consumer R fromSession(SessionFactoryImplementor sfi, Function action) { - log.trace( "#inSession(SF,action)" ); + log.trace( "#fromSession(SF,action)" ); try (SessionImplementor session = sfi.openSession()) { log.trace( "Session opened, calling action" ); @@ -75,7 +75,7 @@ public static void inTransaction(SessionFactoryImplementor factory, Consumer R fromTransaction(SessionFactoryImplementor factory, Function action) { - log.trace( "#inTransaction(factory, action)"); + log.trace( "#fromTransaction(factory, action)"); return fromSession( factory, @@ -133,7 +133,7 @@ public static void inTransaction(SessionImplementor session, Consumer R fromTransaction(SessionImplementor session, Function action) { - log.trace( "inTransaction(session,action)" ); + log.trace( "fromTransaction(session,action)" ); final Transaction txn = session.beginTransaction(); log.trace( "Started transaction" ); From 8ba81d410797400449218859596eefd9dab09d35 Mon Sep 17 00:00:00 2001 From: Gavin King Date: Sun, 13 Jul 2025 03:31:03 +0200 Subject: [PATCH 03/32] change how HQL functions are logged at startup put them all in a single log message --- .../java/org/hibernate/query/internal/QueryEngineImpl.java | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/hibernate-core/src/main/java/org/hibernate/query/internal/QueryEngineImpl.java b/hibernate-core/src/main/java/org/hibernate/query/internal/QueryEngineImpl.java index e6e7cc6d7828..6d366ead6cae 100644 --- a/hibernate-core/src/main/java/org/hibernate/query/internal/QueryEngineImpl.java +++ b/hibernate-core/src/main/java/org/hibernate/query/internal/QueryEngineImpl.java @@ -148,8 +148,12 @@ private static SqmFunctionRegistry createFunctionRegistry( dialect.initializeFunctionRegistry( functionContributions ); if ( LOG_HQL_FUNCTIONS.isDebugEnabled() ) { + var list = new StringBuilder("Available HQL Functions:\n"); sqmFunctionRegistry.getFunctionsByName() - .forEach( entry -> LOG_HQL_FUNCTIONS.debug( entry.getValue().getSignature( entry.getKey() ) ) ); + .forEach( entry -> list.append('\t') + .append( entry.getValue().getSignature( entry.getKey() ) ) + .append('\n') ); + LOG_HQL_FUNCTIONS.debug( list.toString() ); } return sqmFunctionRegistry; From a3119037ad84fa2564b770f903fca31000f447fa Mon Sep 17 00:00:00 2001 From: Gavin King Date: Sun, 13 Jul 2025 03:32:24 +0200 Subject: [PATCH 04/32] avoid use of deprecated service lookup because it results in logging telling us not to do it --- .../register-event-listeners-example.java | 2 +- .../boot/beanvalidation/TypeSafeActivator.java | 2 +- .../hibernate/boot/internal/MetadataImpl.java | 9 +++------ .../orm/test/bootstrap/BootstrapTest.java | 5 ++--- .../events/LegacyPostCommitListenerTest.java | 18 +++++++----------- .../test/events/PostCommitListenerTest.java | 18 +++++++----------- ...llectionListenerInStatelessSessionTest.java | 6 +----- .../envers/boot/internal/EnversIntegrator.java | 2 +- .../basic/RegisterUserEventListenersTest.java | 3 +-- 9 files changed, 24 insertions(+), 41 deletions(-) diff --git a/documentation/src/main/asciidoc/integrationguide/chapters/services/extras/register-event-listeners-example.java b/documentation/src/main/asciidoc/integrationguide/chapters/services/extras/register-event-listeners-example.java index 7231d09939e3..49fbd110d3c8 100644 --- a/documentation/src/main/asciidoc/integrationguide/chapters/services/extras/register-event-listeners-example.java +++ b/documentation/src/main/asciidoc/integrationguide/chapters/services/extras/register-event-listeners-example.java @@ -6,7 +6,7 @@ public void integrate( SessionFactoryServiceRegistry serviceRegistry) { // As you might expect, an EventListenerRegistry is the thing with which event listeners are registered It is a // service so we look it up using the service registry - final EventListenerRegistry eventListenerRegistry = serviceRegistry.getService( EventListenerRegistry.class ); + final EventListenerRegistry eventListenerRegistry = sessionFactory.getEventListenerRegistry(); // If you wish to have custom determination and handling of "duplicate" listeners, you would have to add an // implementation of the org.hibernate.event.service.spi.DuplicationStrategy contract like this diff --git a/hibernate-core/src/main/java/org/hibernate/boot/beanvalidation/TypeSafeActivator.java b/hibernate-core/src/main/java/org/hibernate/boot/beanvalidation/TypeSafeActivator.java index 9a220f8c7df1..f84df1666210 100644 --- a/hibernate-core/src/main/java/org/hibernate/boot/beanvalidation/TypeSafeActivator.java +++ b/hibernate-core/src/main/java/org/hibernate/boot/beanvalidation/TypeSafeActivator.java @@ -158,7 +158,7 @@ private static void setupListener(ValidatorFactory validatorFactory, SessionFact final ConfigurationService cfgService = serviceRegistry.requireService( ConfigurationService.class ); final BeanValidationEventListener listener = new BeanValidationEventListener( validatorFactory, cfgService.getSettings(), classLoaderService ); - final EventListenerRegistry listenerRegistry = serviceRegistry.requireService( EventListenerRegistry.class ); + final EventListenerRegistry listenerRegistry = sessionFactory.getEventListenerRegistry(); listenerRegistry.addDuplicationStrategy( DuplicationStrategyImpl.INSTANCE ); listenerRegistry.appendListeners( EventType.PRE_INSERT, listener ); listenerRegistry.appendListeners( EventType.PRE_UPDATE, listener ); diff --git a/hibernate-core/src/main/java/org/hibernate/boot/internal/MetadataImpl.java b/hibernate-core/src/main/java/org/hibernate/boot/internal/MetadataImpl.java index 8e12c2900be6..15dd36715c71 100644 --- a/hibernate-core/src/main/java/org/hibernate/boot/internal/MetadataImpl.java +++ b/hibernate-core/src/main/java/org/hibernate/boot/internal/MetadataImpl.java @@ -493,12 +493,9 @@ public void initSessionFactory(SessionFactoryImplementor sessionFactory) { // must not use BootstrapContext services here final ServiceRegistryImplementor registry = sessionFactory.getServiceRegistry(); assert registry != null; - final ConfigurationService configurationService = - registry.requireService( ConfigurationService.class ); - final ClassLoaderService classLoaderService = - registry.requireService( ClassLoaderService.class ); - final EventListenerRegistry eventListenerRegistry = - registry.requireService( EventListenerRegistry.class ); + final ConfigurationService configurationService = registry.requireService( ConfigurationService.class ); + final ClassLoaderService classLoaderService = registry.requireService( ClassLoaderService.class ); + final EventListenerRegistry eventListenerRegistry = sessionFactory.getEventListenerRegistry(); configurationService.getSettings().forEach( (propertyName, value) -> { if ( propertyName.startsWith( EVENT_LISTENER_PREFIX ) ) { final String eventTypeName = propertyName.substring( EVENT_LISTENER_PREFIX.length() + 1 ); diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/bootstrap/BootstrapTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/bootstrap/BootstrapTest.java index 92c665d76629..5073f9edd2b6 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/bootstrap/BootstrapTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/bootstrap/BootstrapTest.java @@ -498,9 +498,8 @@ public void integrate( // As you might expect, an EventListenerRegistry is the thing with which event // listeners are registered - // It is a service so we look it up using the service registry - final EventListenerRegistry eventListenerRegistry = - bootstrapContext.getServiceRegistry().getService(EventListenerRegistry.class); + // It is a service, so we look it up using the service registry + final EventListenerRegistry eventListenerRegistry = sessionFactory.getEventListenerRegistry(); // If you wish to have custom determination and handling of "duplicate" listeners, // you would have to add an implementation of the diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/events/LegacyPostCommitListenerTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/events/LegacyPostCommitListenerTest.java index 877c78f504c4..de3c0961cbaa 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/events/LegacyPostCommitListenerTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/events/LegacyPostCommitListenerTest.java @@ -21,7 +21,6 @@ import org.hibernate.event.spi.PostUpdateEventListener; import org.hibernate.integrator.spi.Integrator; import org.hibernate.persister.entity.EntityPersister; -import org.hibernate.service.spi.ServiceRegistryImplementor; import org.hibernate.testing.orm.junit.JiraKey; import org.hibernate.testing.junit4.BaseCoreFunctionalTestCase; @@ -59,16 +58,13 @@ public void integrate( } private void integrate(SessionFactoryImplementor sessionFactory) { - final ServiceRegistryImplementor serviceRegistry = sessionFactory.getServiceRegistry(); - serviceRegistry.getService( EventListenerRegistry.class ).getEventListenerGroup( - EventType.POST_COMMIT_DELETE - ).appendListener( postCommitDeleteEventListener ); - serviceRegistry.getService( EventListenerRegistry.class ).getEventListenerGroup( - EventType.POST_COMMIT_UPDATE - ).appendListener( postCommitUpdateEventListener ); - serviceRegistry.getService( EventListenerRegistry.class ).getEventListenerGroup( - EventType.POST_COMMIT_INSERT - ).appendListener( postCommitInsertEventListener ); + final EventListenerRegistry listenerRegistry = sessionFactory.getEventListenerRegistry(); + listenerRegistry.getEventListenerGroup( EventType.POST_COMMIT_DELETE ) + .appendListener( postCommitDeleteEventListener ); + listenerRegistry.getEventListenerGroup( EventType.POST_COMMIT_UPDATE ) + .appendListener( postCommitUpdateEventListener ); + listenerRegistry.getEventListenerGroup( EventType.POST_COMMIT_INSERT ) + .appendListener( postCommitInsertEventListener ); } } ); diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/events/PostCommitListenerTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/events/PostCommitListenerTest.java index 35dc6904e335..80c0e528a706 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/events/PostCommitListenerTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/events/PostCommitListenerTest.java @@ -24,7 +24,6 @@ import org.hibernate.event.spi.PostUpdateEventListener; import org.hibernate.integrator.spi.Integrator; import org.hibernate.persister.entity.EntityPersister; -import org.hibernate.service.spi.ServiceRegistryImplementor; import org.hibernate.testing.orm.junit.JiraKey; import org.hibernate.testing.junit4.BaseCoreFunctionalTestCase; @@ -65,16 +64,13 @@ public void integrate( } private void integrate(SessionFactoryImplementor sessionFactory) { - final ServiceRegistryImplementor serviceRegistry = sessionFactory.getServiceRegistry(); - serviceRegistry.getService( EventListenerRegistry.class ).getEventListenerGroup( - EventType.POST_COMMIT_DELETE - ).appendListener( postCommitDeleteEventListener ); - serviceRegistry.getService( EventListenerRegistry.class ).getEventListenerGroup( - EventType.POST_COMMIT_UPDATE - ).appendListener( postCommitUpdateEventListener ); - serviceRegistry.getService( EventListenerRegistry.class ).getEventListenerGroup( - EventType.POST_COMMIT_INSERT - ).appendListener( postCommitInsertEventListener ); + final EventListenerRegistry listenerRegistry = sessionFactory.getEventListenerRegistry(); + listenerRegistry.getEventListenerGroup( EventType.POST_COMMIT_DELETE ) + .appendListener( postCommitDeleteEventListener ); + listenerRegistry.getEventListenerGroup( EventType.POST_COMMIT_UPDATE ) + .appendListener( postCommitUpdateEventListener ); + listenerRegistry.getEventListenerGroup( EventType.POST_COMMIT_INSERT ) + .appendListener( postCommitInsertEventListener ); } } ); diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/stateless/events/CollectionListenerInStatelessSessionTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/stateless/events/CollectionListenerInStatelessSessionTest.java index a29443efec85..7d322d50ac31 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/stateless/events/CollectionListenerInStatelessSessionTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/stateless/events/CollectionListenerInStatelessSessionTest.java @@ -4,8 +4,6 @@ */ package org.hibernate.orm.test.stateless.events; -import org.hibernate.engine.spi.SessionFactoryImplementor; -import org.hibernate.event.service.spi.EventListenerRegistry; import org.hibernate.event.spi.EventType; import org.hibernate.event.spi.PostCollectionRecreateEvent; import org.hibernate.event.spi.PostCollectionRecreateEventListener; @@ -28,9 +26,7 @@ class CollectionListenerInStatelessSessionTest { @Test void statelessInsert(SessionFactoryScope scope) { - EventListenerRegistry registry = - scope.getSessionFactory().unwrap(SessionFactoryImplementor.class) - .getServiceRegistry().getService(EventListenerRegistry.class); + var registry = scope.getSessionFactory().getEventListenerRegistry(); var preRecreate = new MyPreCollectionRecreateEventListener(); var preRemove = new MyPreCollectionRemoveEventListener(); var postRecreate = new MyPostCollectionRecreateEventListener(); diff --git a/hibernate-envers/src/main/java/org/hibernate/envers/boot/internal/EnversIntegrator.java b/hibernate-envers/src/main/java/org/hibernate/envers/boot/internal/EnversIntegrator.java index 64dabacda00e..915b53f34b77 100644 --- a/hibernate-envers/src/main/java/org/hibernate/envers/boot/internal/EnversIntegrator.java +++ b/hibernate-envers/src/main/java/org/hibernate/envers/boot/internal/EnversIntegrator.java @@ -81,7 +81,7 @@ public void integrate( // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // Do the registrations - final EventListenerRegistry listenerRegistry = serviceRegistry.getService( EventListenerRegistry.class ); + final EventListenerRegistry listenerRegistry = sessionFactory.getEventListenerRegistry(); listenerRegistry.addDuplicationStrategy( EnversListenerDuplicationStrategy.INSTANCE ); if ( enversService.getEntitiesConfigurations().hasAuditedEntities() ) { diff --git a/hibernate-envers/src/test/java/org/hibernate/orm/test/envers/integration/basic/RegisterUserEventListenersTest.java b/hibernate-envers/src/test/java/org/hibernate/orm/test/envers/integration/basic/RegisterUserEventListenersTest.java index 82512f6efb70..ea124946b8e5 100644 --- a/hibernate-envers/src/test/java/org/hibernate/orm/test/envers/integration/basic/RegisterUserEventListenersTest.java +++ b/hibernate-envers/src/test/java/org/hibernate/orm/test/envers/integration/basic/RegisterUserEventListenersTest.java @@ -33,8 +33,7 @@ protected Class[] getAnnotatedClasses() { @Test @JiraKey(value = "HHH-7478") public void testTransactionProcessSynchronization() { - final EventListenerRegistry registry = sessionFactory().getServiceRegistry() - .getService( EventListenerRegistry.class ); + final EventListenerRegistry registry = sessionFactory().getEventListenerRegistry(); final CountingPostInsertTransactionBoundaryListener listener = new CountingPostInsertTransactionBoundaryListener(); registry.getEventListenerGroup( EventType.POST_INSERT ).appendListener( listener ); From 7495085367101bba66b1e807289f64e55dfb2cef Mon Sep 17 00:00:00 2001 From: Gavin King Date: Sun, 13 Jul 2025 03:37:25 +0200 Subject: [PATCH 05/32] downgrade two more DEBUG-level messages to TRACE --- .../platform/internal/JtaPlatformInitiator.java | 15 ++++++++------- .../internal/JtaPlatformResolverInitiator.java | 2 +- .../internal/StandardJtaPlatformResolver.java | 2 +- 3 files changed, 10 insertions(+), 9 deletions(-) diff --git a/hibernate-core/src/main/java/org/hibernate/engine/transaction/jta/platform/internal/JtaPlatformInitiator.java b/hibernate-core/src/main/java/org/hibernate/engine/transaction/jta/platform/internal/JtaPlatformInitiator.java index 306822cbb0cd..bded3891aa69 100644 --- a/hibernate-core/src/main/java/org/hibernate/engine/transaction/jta/platform/internal/JtaPlatformInitiator.java +++ b/hibernate-core/src/main/java/org/hibernate/engine/transaction/jta/platform/internal/JtaPlatformInitiator.java @@ -37,25 +37,26 @@ public Class getServiceInitiated() { @Override public @Nullable JtaPlatform initiateService(Map configurationValues, ServiceRegistryImplementor registry) { final Object setting = configurationValues.get( AvailableSettings.JTA_PLATFORM ); - JtaPlatform platform = registry.requireService( StrategySelector.class ) - .resolveStrategy( JtaPlatform.class, setting ); + JtaPlatform platform = + registry.requireService( StrategySelector.class ) + .resolveStrategy( JtaPlatform.class, setting ); if ( platform == null ) { - LOG.debug( "No JtaPlatform was specified, checking resolver" ); + LOG.trace( "No JtaPlatform was specified, checking resolver" ); platform = registry.requireService( JtaPlatformResolver.class ) .resolveJtaPlatform( configurationValues, registry ); } if ( platform == null ) { - LOG.debug( "No JtaPlatform was specified, checking fallback provider" ); + LOG.trace( "No JtaPlatform was specified, checking fallback provider" ); platform = getFallbackProvider( configurationValues, registry ); } - if ( platform != null && !(platform instanceof NoJtaPlatform) ) { - LOG.usingJtaPlatform( platform.getClass().getName() ); + if ( platform == null || platform instanceof NoJtaPlatform ) { + LOG.noJtaPlatform(); } else { - LOG.noJtaPlatform(); + LOG.usingJtaPlatform( platform.getClass().getName() ); } return platform; } diff --git a/hibernate-core/src/main/java/org/hibernate/engine/transaction/jta/platform/internal/JtaPlatformResolverInitiator.java b/hibernate-core/src/main/java/org/hibernate/engine/transaction/jta/platform/internal/JtaPlatformResolverInitiator.java index 35593d12af5f..6183b07bc42b 100644 --- a/hibernate-core/src/main/java/org/hibernate/engine/transaction/jta/platform/internal/JtaPlatformResolverInitiator.java +++ b/hibernate-core/src/main/java/org/hibernate/engine/transaction/jta/platform/internal/JtaPlatformResolverInitiator.java @@ -29,7 +29,7 @@ public JtaPlatformResolver initiateService(Map configurationValu registry.requireService( StrategySelector.class ) .resolveStrategy( JtaPlatformResolver.class, setting ); if ( resolver == null ) { - log.debugf( "No JtaPlatformResolver was specified, using default [%s]", StandardJtaPlatformResolver.class.getName() ); + log.tracef( "No JtaPlatformResolver was specified, using default [%s]", StandardJtaPlatformResolver.class.getName() ); return StandardJtaPlatformResolver.INSTANCE; } return resolver; diff --git a/hibernate-core/src/main/java/org/hibernate/engine/transaction/jta/platform/internal/StandardJtaPlatformResolver.java b/hibernate-core/src/main/java/org/hibernate/engine/transaction/jta/platform/internal/StandardJtaPlatformResolver.java index 303121faca07..095a04fa65c5 100644 --- a/hibernate-core/src/main/java/org/hibernate/engine/transaction/jta/platform/internal/StandardJtaPlatformResolver.java +++ b/hibernate-core/src/main/java/org/hibernate/engine/transaction/jta/platform/internal/StandardJtaPlatformResolver.java @@ -97,7 +97,7 @@ public JtaPlatform resolveJtaPlatform(Map configurationValues, ServiceRegis } // Finally, return the default... - log.debugf( "Could not resolve JtaPlatform, using default [%s]", NoJtaPlatform.class.getName() ); + log.tracef( "Could not resolve JtaPlatform, using default [%s]", NoJtaPlatform.class.getName() ); return NoJtaPlatform.INSTANCE; } } From d5ec2f609ca9a5ff562d52fd5264394158b3de72 Mon Sep 17 00:00:00 2001 From: Gavin King Date: Sun, 13 Jul 2025 08:39:09 +0200 Subject: [PATCH 06/32] very minor code cleanups in ResourceRegistryStandardImpl --- .../ResourceRegistryStandardImpl.java | 44 ++++++++++--------- 1 file changed, 23 insertions(+), 21 deletions(-) diff --git a/hibernate-core/src/main/java/org/hibernate/resource/jdbc/internal/ResourceRegistryStandardImpl.java b/hibernate-core/src/main/java/org/hibernate/resource/jdbc/internal/ResourceRegistryStandardImpl.java index 02344d3bf559..fff2f270e844 100644 --- a/hibernate-core/src/main/java/org/hibernate/resource/jdbc/internal/ResourceRegistryStandardImpl.java +++ b/hibernate-core/src/main/java/org/hibernate/resource/jdbc/internal/ResourceRegistryStandardImpl.java @@ -136,19 +136,18 @@ public void release(ResultSet resultSet, Statement statement) { close( resultSet ); } - private static void closeAll(final ResultSetsSet resultSets) { - if ( resultSets == null ) { - return; + private static void closeAll(ResultSetsSet resultSets) { + if ( resultSets != null ) { + resultSets.forEachResultSet( ResourceRegistryStandardImpl::close ); } - resultSets.forEachResultSet( ResourceRegistryStandardImpl::close ); } - private static void releaseXref(final Statement s, final ResultSetsSet r) { - closeAll( r ); - close( s ); + private static void releaseXref(Statement statement, ResultSetsSet resultSetsSet) { + closeAll( resultSetsSet ); + close( statement ); } - private static void close(final ResultSet resultSet) { + private static void close(ResultSet resultSet) { if ( IS_TRACE_ENABLED ) { log.tracef( "Closing result set [%s]", resultSet ); } @@ -225,10 +224,10 @@ public void register(ResultSet resultSet, Statement statement) { } private ExtendedState getExtendedStateForWrite() { - if ( this.ext == null ) { - this.ext = new ExtendedState(); + if ( ext == null ) { + ext = new ExtendedState(); } - return this.ext; + return ext; } private JDBCException convert(SQLException e, String s) { @@ -242,11 +241,12 @@ public void register(Blob blob) { @Override public void release(final Blob blob) { - if ( ext == null || ext.blobs == null ) { + if ( ext != null && ext.blobs != null ) { + ext.blobs.remove( blob ); + } + else { log.debug( "Request to release Blob, but appears no Blobs have ever been registered" ); - return; } - ext.blobs.remove( blob ); } @Override @@ -256,11 +256,12 @@ public void register(final Clob clob) { @Override public void release(final Clob clob) { - if ( ext == null || ext.clobs == null ) { + if ( ext != null && ext.clobs != null ) { + ext.clobs.remove( clob ); + } + else { log.debug( "Request to release Clob, but appears no Clobs have ever been registered" ); - return; } - ext.clobs.remove( clob ); } @Override @@ -272,11 +273,12 @@ public void register(final NClob nclob) { @Override public void release(NClob nclob) { // todo : just store them in clobs? - if ( ext == null || ext.nclobs == null ) { + if ( ext != null && ext.nclobs != null ) { + ext.nclobs.remove( nclob ); + } + else { log.debug( "Request to release NClob, but appears no NClobs have ever been registered" ); - return; } - ext.nclobs.remove( nclob ); } @Override @@ -318,7 +320,7 @@ private static boolean hasRegistered(final ResultSetsSet resource) { return resource != null && !resource.isEmpty(); } - private static boolean hasRegistered(final ArrayList resource) { + private static boolean hasRegistered(final ArrayList resource) { return resource != null && !resource.isEmpty(); } From 6b9a6d374ba5aeefc224864a33d1bd02b0104a65 Mon Sep 17 00:00:00 2001 From: Gavin King Date: Sun, 13 Jul 2025 08:40:02 +0200 Subject: [PATCH 07/32] very minor code cleanups in ManagedTypeProcessor --- .../xml/internal/ManagedTypeProcessor.java | 59 ++++++++----------- 1 file changed, 23 insertions(+), 36 deletions(-) diff --git a/hibernate-core/src/main/java/org/hibernate/boot/models/xml/internal/ManagedTypeProcessor.java b/hibernate-core/src/main/java/org/hibernate/boot/models/xml/internal/ManagedTypeProcessor.java index c9d19eb7688d..831be5b28700 100644 --- a/hibernate-core/src/main/java/org/hibernate/boot/models/xml/internal/ManagedTypeProcessor.java +++ b/hibernate-core/src/main/java/org/hibernate/boot/models/xml/internal/ManagedTypeProcessor.java @@ -5,7 +5,6 @@ package org.hibernate.boot.models.xml.internal; import java.util.List; -import java.util.function.Supplier; import org.hibernate.MappingException; import org.hibernate.annotations.CacheConcurrencyStrategy; @@ -36,7 +35,6 @@ import org.hibernate.boot.models.xml.spi.XmlDocumentContext; import org.hibernate.boot.models.xml.spi.XmlProcessingResult; import org.hibernate.internal.util.StringHelper; -import org.hibernate.internal.util.collections.CollectionHelper; import org.hibernate.models.ModelsException; import org.hibernate.models.internal.ClassTypeDetailsImpl; import org.hibernate.models.internal.ModelsClassLogging; @@ -62,6 +60,7 @@ import static org.hibernate.internal.util.NullnessHelper.coalesce; import static org.hibernate.internal.util.NullnessHelper.coalesceSuppliedValues; import static org.hibernate.internal.util.StringHelper.isNotEmpty; +import static org.hibernate.internal.util.collections.CollectionHelper.isNotEmpty; /** * Helper for handling managed types defined in mapping XML, in either @@ -322,7 +321,10 @@ private static void applyAccessAnnotation( AccessType accessType, MutableClassDetails target, XmlDocumentContext xmlDocumentContext) { - final AccessJpaAnnotation annotationUsage = (AccessJpaAnnotation) target.applyAnnotationUsage( JpaAnnotations.ACCESS, xmlDocumentContext.getModelBuildingContext() ); + final AccessJpaAnnotation annotationUsage = + (AccessJpaAnnotation) + target.applyAnnotationUsage( JpaAnnotations.ACCESS, + xmlDocumentContext.getModelBuildingContext() ); annotationUsage.value( accessType ); target.addAnnotationUsage( annotationUsage ); } @@ -332,10 +334,10 @@ private static void applyCaching( MutableClassDetails classDetails, XmlDocumentContext xmlDocumentContext) { if ( jaxbEntity.isCacheable() != null ) { - final CacheableJpaAnnotation cacheableUsage = (CacheableJpaAnnotation) classDetails.applyAnnotationUsage( - JpaAnnotations.CACHEABLE, - xmlDocumentContext.getModelBuildingContext() - ); + final CacheableJpaAnnotation cacheableUsage = + (CacheableJpaAnnotation) + classDetails.applyAnnotationUsage( JpaAnnotations.CACHEABLE, + xmlDocumentContext.getModelBuildingContext() ); cacheableUsage.value( jaxbEntity.isCacheable() ); classDetails.addAnnotationUsage( cacheableUsage ); @@ -343,10 +345,10 @@ private static void applyCaching( final JaxbCachingImpl jaxbCaching = jaxbEntity.getCaching(); if ( jaxbCaching != null ) { - final CacheAnnotation cacheUsage = (CacheAnnotation) classDetails.replaceAnnotationUsage( - HibernateAnnotations.CACHE, - xmlDocumentContext.getModelBuildingContext() - ); + final CacheAnnotation cacheUsage = + (CacheAnnotation) + classDetails.replaceAnnotationUsage( HibernateAnnotations.CACHE, + xmlDocumentContext.getModelBuildingContext() ); if ( StringHelper.isNotEmpty( jaxbCaching.getRegion() ) ) { cacheUsage.region( jaxbCaching.getRegion() ); } @@ -360,10 +362,7 @@ private static void applyCaching( } private static CacheConcurrencyStrategy convertCacheAccessType(org.hibernate.cache.spi.access.AccessType accessType) { - if ( accessType == null ) { - return null; - } - return CacheConcurrencyStrategy.fromAccessType( accessType ); + return accessType == null ? null : CacheConcurrencyStrategy.fromAccessType( accessType ); } private static void applyTenantId( @@ -378,7 +377,8 @@ private static void applyTenantId( coalesce( jaxbTenantId.getAccess(), classAccessType ), classDetails ); - memberDetails.applyAnnotationUsage( HibernateAnnotations.TENANT_ID, xmlDocumentContext.getModelBuildingContext() ); + memberDetails.applyAnnotationUsage( HibernateAnnotations.TENANT_ID, + xmlDocumentContext.getModelBuildingContext() ); BasicAttributeProcessing.processBasicAttribute( jaxbTenantId, classDetails, @@ -418,10 +418,11 @@ public static void processOverrideEntity(List @@ -453,11 +454,8 @@ public static void processOverrideEntity(List - * According to the specification, strictly speaking, this should (could) be an exception - */ - private static Supplier determineAccessTypeFromClassAndXml( - JaxbEntityImpl jaxbEntity, - MutableClassDetails classDetails) { - return null; - } - private static void processIdMappings( JaxbAttributesContainerImpl attributes, AccessType classAccessType, @@ -499,7 +486,7 @@ private static void processIdMappings( final List jaxbIds = attributes.getIdAttributes(); final JaxbEmbeddedIdImpl jaxbEmbeddedId = attributes.getEmbeddedIdAttribute(); - if ( CollectionHelper.isNotEmpty( jaxbIds ) ) { + if ( isNotEmpty( jaxbIds ) ) { for ( int i = 0; i < jaxbIds.size(); i++ ) { final JaxbIdImpl jaxbId = jaxbIds.get( i ); final MutableMemberDetails memberDetails = BasicIdAttributeProcessing.processBasicIdAttribute( From 0e14088d8868d4203a3123590dc97e2e31b7e68c Mon Sep 17 00:00:00 2001 From: Gavin King Date: Sun, 13 Jul 2025 09:21:51 +0200 Subject: [PATCH 08/32] introduce ResourceRegistryLogger and clean up some Logger descriptions --- .../boot/query/BootQueryLogging.java | 2 +- .../jdbc/env/internal/LobCreationLogging.java | 2 +- .../graph/internal/GraphParserLogging.java | 2 +- .../hibernate/internal/CoreMessageLogger.java | 10 -- .../internal/log/ConnectionAccessLogger.java | 2 +- .../org/hibernate/loader/LoaderLogging.java | 3 +- .../jdbc/internal/ResourceRegistryLogger.java | 104 ++++++++++++++++++ .../ResourceRegistryStandardImpl.java | 66 +++++------ .../sql/model/ModelMutationLogging.java | 2 +- .../hibernate/sql/results/ResultsLogger.java | 2 +- 10 files changed, 144 insertions(+), 51 deletions(-) create mode 100644 hibernate-core/src/main/java/org/hibernate/resource/jdbc/internal/ResourceRegistryLogger.java diff --git a/hibernate-core/src/main/java/org/hibernate/boot/query/BootQueryLogging.java b/hibernate-core/src/main/java/org/hibernate/boot/query/BootQueryLogging.java index 41bb950be60f..152893a82417 100644 --- a/hibernate-core/src/main/java/org/hibernate/boot/query/BootQueryLogging.java +++ b/hibernate-core/src/main/java/org/hibernate/boot/query/BootQueryLogging.java @@ -15,7 +15,7 @@ */ @SubSystemLogging( name = BootQueryLogging.NAME, - description = "Logging related to processing of named-queries" + description = "Logging related to processing of named queries" ) @Internal public interface BootQueryLogging { diff --git a/hibernate-core/src/main/java/org/hibernate/engine/jdbc/env/internal/LobCreationLogging.java b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/env/internal/LobCreationLogging.java index 3be5f6684b96..ea0d146ea4f8 100644 --- a/hibernate-core/src/main/java/org/hibernate/engine/jdbc/env/internal/LobCreationLogging.java +++ b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/env/internal/LobCreationLogging.java @@ -25,7 +25,7 @@ */ @SubSystemLogging( name = BootLogging.NAME, - description = "Logging related to " + description = "Logging related to contextual LOB creation" ) @MessageLogger( projectCode = "HHH" ) @ValidIdRange( min = 10010001, max = 10010050 ) diff --git a/hibernate-core/src/main/java/org/hibernate/graph/internal/GraphParserLogging.java b/hibernate-core/src/main/java/org/hibernate/graph/internal/GraphParserLogging.java index 8a2e7357b5a4..d262e3534d43 100644 --- a/hibernate-core/src/main/java/org/hibernate/graph/internal/GraphParserLogging.java +++ b/hibernate-core/src/main/java/org/hibernate/graph/internal/GraphParserLogging.java @@ -14,7 +14,7 @@ */ @SubSystemLogging( name = GraphParserLogging.LOGGER_NAME, - description = "Logging related to Hibernate's `GraphParser` for parsing entity-graphs from String representations" + description = "Logging related to GraphParser for parsing entity graphs from String representations" ) @Internal public interface GraphParserLogging { diff --git a/hibernate-core/src/main/java/org/hibernate/internal/CoreMessageLogger.java b/hibernate-core/src/main/java/org/hibernate/internal/CoreMessageLogger.java index 0fcdf01cf583..767c776cfdff 100644 --- a/hibernate-core/src/main/java/org/hibernate/internal/CoreMessageLogger.java +++ b/hibernate-core/src/main/java/org/hibernate/internal/CoreMessageLogger.java @@ -474,16 +474,6 @@ void missingArguments( @Message(value = "I/O reported error writing cached file: %s: %s", id = 378) void unableToWriteCachedFile(String path, String message); - @LogMessage(level = WARN) - @Message(value = "ResultSet had no statement associated with it, but was not yet registered", id = 386) - void unregisteredResultSetWithoutStatement(); - - // Keep this at DEBUG level, rather than warn. Numerous connection pool implementations can return a - // proxy/wrapper around the JDBC Statement, causing excessive logging here. See HHH-8210. - @LogMessage(level = DEBUG) - @Message(value = "ResultSet's statement was not registered", id = 387) - void unregisteredStatement(); - @LogMessage(level = WARN) @Message(value = "The %s.%s.%s version of H2 implements temporary table creation such that it commits current transaction; multi-table, bulk HQL/JPQL will not work properly", id = 393) diff --git a/hibernate-core/src/main/java/org/hibernate/internal/log/ConnectionAccessLogger.java b/hibernate-core/src/main/java/org/hibernate/internal/log/ConnectionAccessLogger.java index 9e46ae7cda76..ee17c0cd9c45 100644 --- a/hibernate-core/src/main/java/org/hibernate/internal/log/ConnectionAccessLogger.java +++ b/hibernate-core/src/main/java/org/hibernate/internal/log/ConnectionAccessLogger.java @@ -24,7 +24,7 @@ @ValidIdRange( min = 10001501, max = 10002000 ) @SubSystemLogging( name = ConnectionAccessLogger.LOGGER_NAME, - description = "Used to log details around use of `JdbcConnectionAccess`" + description = "Logging related to use of JdbcConnectionAccess" ) @Internal public interface ConnectionAccessLogger extends BasicLogger { diff --git a/hibernate-core/src/main/java/org/hibernate/loader/LoaderLogging.java b/hibernate-core/src/main/java/org/hibernate/loader/LoaderLogging.java index 6ca8934c9ce0..f92782f69825 100644 --- a/hibernate-core/src/main/java/org/hibernate/loader/LoaderLogging.java +++ b/hibernate-core/src/main/java/org/hibernate/loader/LoaderLogging.java @@ -18,8 +18,7 @@ */ @SubSystemLogging( name = LoaderLogging.LOGGER_NAME, - description = "Logging related to loaders of domain model references (`org.hibernate.loader.ast.spi.Loader`); " + - "see also `" + SubSystemLogging.BASE + ".results`" + description = "Logging related to loaders of domain model references" ) @Internal public interface LoaderLogging { diff --git a/hibernate-core/src/main/java/org/hibernate/resource/jdbc/internal/ResourceRegistryLogger.java b/hibernate-core/src/main/java/org/hibernate/resource/jdbc/internal/ResourceRegistryLogger.java new file mode 100644 index 000000000000..fa591dd617aa --- /dev/null +++ b/hibernate-core/src/main/java/org/hibernate/resource/jdbc/internal/ResourceRegistryLogger.java @@ -0,0 +1,104 @@ +/* + * SPDX-License-Identifier: Apache-2.0 + * Copyright Red Hat Inc. and Hibernate Authors + */ +package org.hibernate.resource.jdbc.internal; + +import org.hibernate.Internal; +import org.hibernate.internal.log.SubSystemLogging; +import org.jboss.logging.BasicLogger; +import org.jboss.logging.Logger; +import org.jboss.logging.annotations.LogMessage; +import org.jboss.logging.annotations.Message; +import org.jboss.logging.annotations.MessageLogger; +import org.jboss.logging.annotations.ValidIdRange; + +import java.lang.invoke.MethodHandles; +import java.sql.ResultSet; +import java.sql.Statement; + +import static org.jboss.logging.Logger.Level.TRACE; +import static org.jboss.logging.Logger.Level.DEBUG; +import static org.jboss.logging.Logger.Level.WARN; + +/** + * @author Steve Ebersole + */ +@MessageLogger( projectCode = "HHH" ) +@ValidIdRange( min = 10002501, max = 10003000 ) +@SubSystemLogging( + name = ResourceRegistryLogger.LOGGER_NAME, + description = "Logging related to use of ResourceRegistry" +) +@Internal +public interface ResourceRegistryLogger extends BasicLogger { + String LOGGER_NAME = SubSystemLogging.BASE + ".resource.registry"; + + /** + * Static access to the logging instance + */ + ResourceRegistryLogger RESOURCE_REGISTRY_LOGGER = Logger.getMessageLogger( + MethodHandles.lookup(), + ResourceRegistryLogger.class, + LOGGER_NAME + ); + + @LogMessage(level = TRACE) + @Message(value = "Releasing registered JDBC resources", id = 10002501) + void releasingResources(); + + @LogMessage(level = TRACE) + @Message(value = "Registering statement [%s]", id = 10002502) + void registeringStatement(Statement statement); + + @LogMessage(level = TRACE) + @Message(value = "Releasing statement [%s]", id = 10002503) + void releasingStatement(Statement statement); + + @LogMessage(level = TRACE) + @Message(value = "Releasing result set [%s]", id = 10002504) + void releasingResultSet(ResultSet resultSet); + + @LogMessage(level = TRACE) + @Message(value = "Closing result set [%s]", id = 10002505) + void closingResultSet(ResultSet resultSet); + + @LogMessage(level = TRACE) + @Message(value = "Closing prepared statement [%s]", id = 10002506) + void closingPreparedStatement(Statement statement); + + @LogMessage(level = TRACE) + @Message(value = "Registering result set [%s]", id = 10002507) + void registeringResultSet(ResultSet resultSet); + + @LogMessage(level = DEBUG) + @Message(value = "Unable to release JDBC statement [%s]", id = 10002508) + void unableToReleaseStatement(String message); + + @LogMessage(level = DEBUG) + @Message(value = "Unable to release JDBC result set [%s]", id = 10002509) + void unableToReleaseResultSet(String message); + + @LogMessage(level = DEBUG) + @Message(value = "Exception clearing maxRows or queryTimeout for JDBC Statement [%s]", id = 10002510) + void exceptionClearingMaxRowsOrQueryTimeout(String message); + + @LogMessage(level = DEBUG) + @Message(value = "Unable to free '%s' reference [%s]", id = 10002511) + void unableToFreeLob(String lobType, String message); + + // Keep this at DEBUG level, rather than WARN. Many connection pool implementations return + // a proxy/wrapper for the JDBC Statement, causing excessive logging here. See HHH-8210. + @LogMessage(level = DEBUG) + @Message(value = "Statement associated with ResultSet was not registered", id = 10002514) + void unregisteredStatement(); + + @LogMessage(level = WARN) + @Message(value = "ResultSet had no statement associated with it, but was not yet registered", id = 10002515) + void unregisteredResultSetWithoutStatement(); + + @LogMessage(level = DEBUG) + @Message(value = "Request to release '%s', but none have ever been registered", id = 10002516) + void noRegisteredLobs(String lobType); + +} diff --git a/hibernate-core/src/main/java/org/hibernate/resource/jdbc/internal/ResourceRegistryStandardImpl.java b/hibernate-core/src/main/java/org/hibernate/resource/jdbc/internal/ResourceRegistryStandardImpl.java index fff2f270e844..d7947e2bb404 100644 --- a/hibernate-core/src/main/java/org/hibernate/resource/jdbc/internal/ResourceRegistryStandardImpl.java +++ b/hibernate-core/src/main/java/org/hibernate/resource/jdbc/internal/ResourceRegistryStandardImpl.java @@ -13,11 +13,11 @@ import java.util.ArrayList; import org.hibernate.JDBCException; -import org.hibernate.internal.CoreLogging; -import org.hibernate.internal.CoreMessageLogger; import org.hibernate.resource.jdbc.ResourceRegistry; import org.hibernate.resource.jdbc.spi.JdbcEventHandler; +import static org.hibernate.resource.jdbc.internal.ResourceRegistryLogger.RESOURCE_REGISTRY_LOGGER; + /** * Helps to track {@link Statement}s and {@link ResultSet}s which need to be closed. * This class is not threadsafe. @@ -35,8 +35,7 @@ */ public final class ResourceRegistryStandardImpl implements ResourceRegistry { - private static final CoreMessageLogger log = CoreLogging.messageLogger( ResourceRegistryStandardImpl.class ); - private static final boolean IS_TRACE_ENABLED = log.isTraceEnabled(); + private static final boolean IS_TRACE_ENABLED = RESOURCE_REGISTRY_LOGGER.isTraceEnabled(); private final JdbcEventHandler jdbcEventHandler; @@ -62,7 +61,7 @@ public boolean hasRegisteredResources() { @Override public void register(Statement statement, boolean cancelable) { if ( IS_TRACE_ENABLED ) { - log.tracef( "Registering statement [%s]", statement ); + RESOURCE_REGISTRY_LOGGER.registeringStatement(statement); } xref.registerExpectingNew( statement ); @@ -75,7 +74,7 @@ public void register(Statement statement, boolean cancelable) { @Override public void release(Statement statement) { if ( IS_TRACE_ENABLED ) { - log.tracef( "Releasing statement [%s]", statement ); + RESOURCE_REGISTRY_LOGGER.releasingStatement( statement ); } final ResultSetsSet resultSets = xref.remove( statement ); @@ -83,9 +82,7 @@ public void release(Statement statement) { closeAll( resultSets ); } else { - // Keep this at DEBUG level, rather than warn. Numerous connection pool implementations can return a - // proxy/wrapper around the JDBC Statement, causing excessive logging here. See HHH-8210. - log.unregisteredStatement(); + RESOURCE_REGISTRY_LOGGER.unregisteredStatement(); } close( statement ); @@ -98,7 +95,7 @@ public void release(Statement statement) { @Override public void release(ResultSet resultSet, Statement statement) { if ( IS_TRACE_ENABLED ) { - log.tracef( "Releasing result set [%s]", resultSet ); + RESOURCE_REGISTRY_LOGGER.releasingResultSet(resultSet); } if ( statement == null ) { @@ -106,13 +103,13 @@ public void release(ResultSet resultSet, Statement statement) { statement = resultSet.getStatement(); } catch (SQLException e) { - throw convert( e, "unable to access Statement from ResultSet" ); + throw convert( e, "Unable to access Statement from ResultSet" ); } } if ( statement != null ) { final ResultSetsSet resultSets = xref.getForResultSetRemoval( statement ); if ( resultSets == null ) { - log.unregisteredStatement(); + RESOURCE_REGISTRY_LOGGER.unregisteredStatement(); } else { resultSets.removeResultSet( resultSet ); @@ -123,7 +120,7 @@ public void release(ResultSet resultSet, Statement statement) { } } catch (SQLException e) { - log.debugf( "Unable to release JDBC statement [%s]", e.getMessage() ); + RESOURCE_REGISTRY_LOGGER.unableToReleaseStatement( e.getMessage() ); } } } @@ -149,7 +146,7 @@ private static void releaseXref(Statement statement, ResultSetsSet resultSetsSet private static void close(ResultSet resultSet) { if ( IS_TRACE_ENABLED ) { - log.tracef( "Closing result set [%s]", resultSet ); + RESOURCE_REGISTRY_LOGGER.closingResultSet(resultSet); } try { @@ -158,17 +155,17 @@ private static void close(ResultSet resultSet) { } } catch (SQLException e) { - log.debugf( "Unable to release JDBC result set [%s]", e.getMessage() ); + RESOURCE_REGISTRY_LOGGER.unableToReleaseResultSet( e.getMessage() ); } catch (Exception e) { // try to handle general errors more elegantly - log.debugf( "Unable to release JDBC result set [%s]", e.getMessage() ); + RESOURCE_REGISTRY_LOGGER.unableToReleaseResultSet( e.getMessage() ); } } private static void close(Statement statement) { if ( IS_TRACE_ENABLED ) { - log.tracef( "Closing prepared statement [%s]", statement ); + RESOURCE_REGISTRY_LOGGER.closingPreparedStatement(statement); } try { @@ -184,8 +181,8 @@ private static void close(Statement statement) { } catch (SQLException sqle) { // there was a problem "cleaning" the prepared statement - if ( log.isDebugEnabled() ) { - log.debugf( "Exception clearing maxRows/queryTimeout [%s]", sqle.getMessage() ); + if ( RESOURCE_REGISTRY_LOGGER.isDebugEnabled() ) { + RESOURCE_REGISTRY_LOGGER.exceptionClearingMaxRowsOrQueryTimeout( sqle.getMessage() ); } // EARLY EXIT!!! return; @@ -193,18 +190,18 @@ private static void close(Statement statement) { statement.close(); } catch (SQLException e) { - log.debugf( "Unable to release JDBC statement [%s]", e.getMessage() ); + RESOURCE_REGISTRY_LOGGER.unableToReleaseStatement( e.getMessage() ); } catch (Exception e) { // try to handle general errors more elegantly - log.debugf( "Unable to release JDBC statement [%s]", e.getMessage() ); + RESOURCE_REGISTRY_LOGGER.unableToReleaseStatement( e.getMessage() ); } } @Override public void register(ResultSet resultSet, Statement statement) { if ( IS_TRACE_ENABLED ) { - log.tracef( "Registering result set [%s]", resultSet ); + RESOURCE_REGISTRY_LOGGER.registeringResultSet(resultSet); } if ( statement == null ) { @@ -212,7 +209,7 @@ public void register(ResultSet resultSet, Statement statement) { statement = resultSet.getStatement(); } catch (SQLException e) { - throw convert( e, "unable to access Statement from ResultSet" ); + throw convert( e, "Unable to access Statement from ResultSet" ); } } if ( statement != null ) { @@ -245,7 +242,7 @@ public void release(final Blob blob) { ext.blobs.remove( blob ); } else { - log.debug( "Request to release Blob, but appears no Blobs have ever been registered" ); + RESOURCE_REGISTRY_LOGGER.noRegisteredLobs( Blob.class.getSimpleName() ); } } @@ -260,7 +257,7 @@ public void release(final Clob clob) { ext.clobs.remove( clob ); } else { - log.debug( "Request to release Clob, but appears no Clobs have ever been registered" ); + RESOURCE_REGISTRY_LOGGER.noRegisteredLobs( Clob.class.getSimpleName() ); } } @@ -277,7 +274,7 @@ public void release(NClob nclob) { ext.nclobs.remove( nclob ); } else { - log.debug( "Request to release NClob, but appears no NClobs have ever been registered" ); + RESOURCE_REGISTRY_LOGGER.noRegisteredLobs( NClob.class.getSimpleName() ); } } @@ -289,7 +286,7 @@ public void cancelLastQuery() { } } catch (SQLException e) { - throw convert( e, "Cannot cancel query" ); + throw convert( e, "Could not cancel query" ); } finally { lastQuery = null; @@ -298,7 +295,7 @@ public void cancelLastQuery() { @Override public void releaseResources() { - log.trace( "Releasing JDBC resources" ); + RESOURCE_REGISTRY_LOGGER.releasingResources(); if ( jdbcEventHandler != null ) { jdbcEventHandler.jdbcReleaseRegistryResourcesStart(); @@ -345,9 +342,12 @@ public boolean hasRegisteredResources() { } public void releaseUnassociatedResult(final ResultSet resultSet) { - final Object removed = unassociatedResultSets == null ? null : unassociatedResultSets.removeResultSet( resultSet ); + final Object removed = + unassociatedResultSets == null + ? null + : unassociatedResultSets.removeResultSet( resultSet ); if ( removed == null ) { - log.unregisteredResultSetWithoutStatement(); + RESOURCE_REGISTRY_LOGGER.unregisteredResultSetWithoutStatement(); } } @@ -390,7 +390,7 @@ public void releaseResources() { blob.free(); } catch (SQLException e) { - log.debugf( "Unable to free JDBC Blob reference [%s]", e.getMessage() ); + RESOURCE_REGISTRY_LOGGER.unableToFreeLob( Blob.class.getSimpleName(), e.getMessage() ); } } ); //for these, it seems better to null the map rather than clear it: @@ -403,7 +403,7 @@ public void releaseResources() { clob.free(); } catch (SQLException e) { - log.debugf( "Unable to free JDBC Clob reference [%s]", e.getMessage() ); + RESOURCE_REGISTRY_LOGGER.unableToFreeLob( Clob.class.getSimpleName(), e.getMessage() ); } } ); clobs = null; @@ -415,7 +415,7 @@ public void releaseResources() { nclob.free(); } catch (SQLException e) { - log.debugf( "Unable to free JDBC NClob reference [%s]", e.getMessage() ); + RESOURCE_REGISTRY_LOGGER.unableToFreeLob( NClob.class.getSimpleName(), e.getMessage() ); } } ); nclobs = null; diff --git a/hibernate-core/src/main/java/org/hibernate/sql/model/ModelMutationLogging.java b/hibernate-core/src/main/java/org/hibernate/sql/model/ModelMutationLogging.java index 1dd199450992..12cee26d8cf1 100644 --- a/hibernate-core/src/main/java/org/hibernate/sql/model/ModelMutationLogging.java +++ b/hibernate-core/src/main/java/org/hibernate/sql/model/ModelMutationLogging.java @@ -16,7 +16,7 @@ */ @SubSystemLogging( name = ModelMutationLogging.NAME, - description = "Logging related to entity and collection mutations stemming from persistence-context events" + description = "Logging related to entity and collection mutations stemming from persistence context events" ) @Internal public final class ModelMutationLogging { diff --git a/hibernate-core/src/main/java/org/hibernate/sql/results/ResultsLogger.java b/hibernate-core/src/main/java/org/hibernate/sql/results/ResultsLogger.java index c9b360eacf9b..a3fb5e0a438d 100644 --- a/hibernate-core/src/main/java/org/hibernate/sql/results/ResultsLogger.java +++ b/hibernate-core/src/main/java/org/hibernate/sql/results/ResultsLogger.java @@ -29,7 +29,7 @@ @ValidIdRange( min = 90005001, max = 90005100 ) @SubSystemLogging( name = ResultsLogger.LOGGER_NAME, - description = "Logging related to `DomainResult` graphs which build individual parts of the domain model from JDBC or from cache" + description = "Logging related to DomainResult graphs which build individual parts of the domain model from JDBC or from cache" ) @Internal public interface ResultsLogger extends BasicLogger { From e3a06c6a02c443a592c16e255d74b7e9dc804747 Mon Sep 17 00:00:00 2001 From: Gavin King Date: Sun, 13 Jul 2025 09:35:31 +0200 Subject: [PATCH 09/32] move logging in JdbcCoordinatorImpl and LogicalConnectionManagedImpl to JdbcLogging and include SF uuid in log messages --- .../hibernate/engine/jdbc/JdbcLogging.java | 77 ++++++++++++++++++- .../jdbc/internal/JdbcCoordinatorImpl.java | 27 +++---- .../hibernate/internal/CoreMessageLogger.java | 20 ++--- .../internal/SessionFactoryImpl.java | 4 +- .../LogicalConnectionManagedImpl.java | 20 +++-- 5 files changed, 107 insertions(+), 41 deletions(-) diff --git a/hibernate-core/src/main/java/org/hibernate/engine/jdbc/JdbcLogging.java b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/JdbcLogging.java index 1e1bce65e28a..86d31d5740b4 100644 --- a/hibernate-core/src/main/java/org/hibernate/engine/jdbc/JdbcLogging.java +++ b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/JdbcLogging.java @@ -4,11 +4,15 @@ */ package org.hibernate.engine.jdbc; +import org.hibernate.ConnectionReleaseMode; import org.hibernate.Internal; import org.hibernate.internal.log.SubSystemLogging; +import static org.hibernate.cfg.JdbcSettings.CONNECTION_PROVIDER_DISABLES_AUTOCOMMIT; + import org.jboss.logging.BasicLogger; import org.jboss.logging.Logger; +import org.jboss.logging.annotations.Cause; import org.jboss.logging.annotations.LogMessage; import org.jboss.logging.annotations.Message; import org.jboss.logging.annotations.MessageLogger; @@ -16,6 +20,8 @@ import java.lang.invoke.MethodHandles; +import static org.jboss.logging.Logger.Level.DEBUG; +import static org.jboss.logging.Logger.Level.TRACE; import static org.jboss.logging.Logger.Level.WARN; /** @@ -31,7 +37,7 @@ @ValidIdRange(min = 100001, max = 100500) @Internal public interface JdbcLogging extends BasicLogger { - String NAME = "org.hibernate.orm.jdbc"; + String NAME = SubSystemLogging.BASE + ".jdbc"; Logger JDBC_LOGGER = Logger.getLogger( NAME ); JdbcLogging JDBC_MESSAGE_LOGGER = Logger.getMessageLogger( MethodHandles.lookup(), JdbcLogging.class, NAME ); @@ -42,4 +48,73 @@ public interface JdbcLogging extends BasicLogger { value = "JDBC driver did not return the expected number of row counts (%s) - expected %s, but received %s" ) void unexpectedRowCounts(String tableName, int expected, int actual); + + @LogMessage(level = TRACE) + @Message(value = "Created JdbcCoordinator @%s", id = 100002) + void createdJdbcCoordinator(int hashCode); + + @LogMessage(level = TRACE) + @Message(value = "Closing JdbcCoordinator @%s", id = 100003) + void closingJdbcCoordinator(int hashCode); + + @LogMessage(level = TRACE) + @Message(value = "Statement execution complete (connection release mode %s) in JdbcCoordinator @%s", id = 100004) + void statementExecutionComplete(ConnectionReleaseMode connectionReleaseMode, int hashCode); + + @LogMessage(level = TRACE) + @Message(value = "Transaction after begin in JdbcCoordinator @%s", id = 100005) + void transactionAfterBegin(int hashCode); + + @LogMessage(level = TRACE) + @Message(value = "Transaction before completion in JdbcCoordinator @%s", id = 100006) + void transactionBeforeCompletion(int hashCode); + + @LogMessage(level = TRACE) + @Message(value = "Transaction after %s completion in JdbcCoordinator @%s", id = 100007) + void transactionAfterCompletion(String completionStatus, int hashCode); + + @LogMessage(level = DEBUG) + @Message(value = "Closing unreleased batch in JdbcCoordinator @%s", id = 100008) + void closingUnreleasedBatch(int hashCode); + + @LogMessage(level = TRACE) + @Message(value = "Closing logical connection @%s", id = 100009) + void closingLogicalConnection(int hashCode); + + @LogMessage(level = TRACE) + @Message(value = "Closed logical connection @%s", id = 100010) + void logicalConnectionClosed(int hashCode); + + @LogMessage(level = TRACE) + @Message(value = "Skipping aggressive release of JDBC connection @%s from 'afterStatement' due to held resources", id = 100011) + void skipConnectionReleaseAfterStatementDueToResources(int hashCode); + + @LogMessage(level = TRACE) + @Message(value = "Initiating release of JDBC connection @%s from 'afterStatement'", id = 100012) + void initiatingConnectionReleaseAfterStatement(int hashCode); + + @LogMessage(level = TRACE) + @Message(value = "Initiating release of JDBC connection @%s from 'beforeTransactionCompletion'", id = 100013) + void initiatingConnectionReleaseBeforeTransactionCompletion(int hashCode); + + @LogMessage(level = TRACE) + @Message(value = "Initiating release of JDBC connection @%s from 'afterTransaction'", id = 100014) + void initiatingConnectionReleaseAfterTransaction(int hashCode); + + @LogMessage(level = WARN) + @Message(value = "Error before releasing JDBC connection @%s", id = 100015) + void errorBeforeReleasingJdbcConnection(int hashCode, @Cause Throwable e); + + @LogMessage(level = DEBUG) + @Message( + id = 100016, + value = + "'" + CONNECTION_PROVIDER_DISABLES_AUTOCOMMIT + "' " + + """ + was enabled. This setting should only be enabled when JDBC Connections obtained by Hibernate \ + from the ConnectionProvider have auto-commit disabled. Enabling this setting when connections \ + have auto-commit enabled leads to execution of SQL operations outside of any JDBC transaction.\ + """ + ) + void connectionProviderDisablesAutoCommitEnabled(); } diff --git a/hibernate-core/src/main/java/org/hibernate/engine/jdbc/internal/JdbcCoordinatorImpl.java b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/internal/JdbcCoordinatorImpl.java index 9215626da507..851d8fa77a21 100644 --- a/hibernate-core/src/main/java/org/hibernate/engine/jdbc/internal/JdbcCoordinatorImpl.java +++ b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/internal/JdbcCoordinatorImpl.java @@ -17,8 +17,6 @@ import org.hibernate.engine.jdbc.spi.ResultSetReturn; import org.hibernate.engine.jdbc.spi.SqlExceptionHelper; import org.hibernate.engine.jdbc.spi.StatementPreparer; -import org.hibernate.internal.CoreLogging; -import org.hibernate.internal.CoreMessageLogger; import org.hibernate.jdbc.WorkExecutor; import org.hibernate.jdbc.WorkExecutorVisitable; import org.hibernate.resource.jdbc.ResourceRegistry; @@ -38,6 +36,7 @@ import java.util.function.Supplier; import static org.hibernate.ConnectionReleaseMode.AFTER_STATEMENT; +import static org.hibernate.engine.jdbc.JdbcLogging.JDBC_MESSAGE_LOGGER; import static org.hibernate.engine.jdbc.batch.JdbcBatchLogging.BATCH_MESSAGE_LOGGER; /** @@ -48,8 +47,7 @@ * @author Sanne Grinovero */ public class JdbcCoordinatorImpl implements JdbcCoordinator { - private static final CoreMessageLogger LOG = CoreLogging.messageLogger( JdbcCoordinatorImpl.class ); - private static final boolean TRACE_ENABLED = LOG.isTraceEnabled(); + private static final boolean TRACE_ENABLED = JDBC_MESSAGE_LOGGER.isTraceEnabled(); private transient final LogicalConnectionImplementor logicalConnection; private transient final JdbcSessionOwner owner; @@ -82,7 +80,7 @@ public JdbcCoordinatorImpl( this.isUserSuppliedConnection = userSuppliedConnection != null; this.logicalConnection = createLogicalConnection( userSuppliedConnection, owner ); if ( TRACE_ENABLED ) { - LOG.tracef( "Created JdbcCoordinator @%s", hashCode() ); + JDBC_MESSAGE_LOGGER.createdJdbcCoordinator( hashCode() ); } } @@ -105,7 +103,7 @@ private JdbcCoordinatorImpl( this.owner = owner; this.jdbcServices = owner.getJdbcSessionContext().getJdbcServices(); if ( TRACE_ENABLED ) { - LOG.tracef( "Created JdbcCoordinator @%s", hashCode() ); + JDBC_MESSAGE_LOGGER.createdJdbcCoordinator( hashCode() ); } } @@ -149,12 +147,12 @@ public void flushEnding() { @Override public Connection close() { if ( TRACE_ENABLED ) { - LOG.tracef( "Closing JdbcCoordinator @%s", hashCode() ); + JDBC_MESSAGE_LOGGER.closingJdbcCoordinator( hashCode() ); } Connection connection; try { if ( currentBatch != null ) { - LOG.closingUnreleasedBatch(); + JDBC_MESSAGE_LOGGER.closingUnreleasedBatch( hashCode() ); currentBatch.release(); } } @@ -275,15 +273,14 @@ public int determineRemainingTransactionTimeOutPeriod() { public void afterStatementExecution() { final ConnectionReleaseMode connectionReleaseMode = connectionReleaseMode(); if ( TRACE_ENABLED ) { - LOG.tracef( "Statement execution complete (connection release mode %s) in JdbcCoordinator @%s", - connectionReleaseMode, hashCode() ); + JDBC_MESSAGE_LOGGER.statementExecutionComplete( connectionReleaseMode, hashCode() ); } if ( connectionReleaseMode == AFTER_STATEMENT ) { if ( ! releasesEnabled ) { - LOG.debug( "Skipping aggressive release due to manual disabling" ); + JDBC_MESSAGE_LOGGER.trace( "Skipping aggressive release due to manual disabling" ); } else if ( hasRegisteredResources() ) { - LOG.debug( "Skipping aggressive release due to registered resources" ); + JDBC_MESSAGE_LOGGER.trace( "Skipping aggressive release due to registered resources" ); } else { getLogicalConnection().afterStatement(); @@ -384,7 +381,7 @@ public boolean isActive() { @Override public void afterTransactionBegin() { if ( TRACE_ENABLED ) { - LOG.tracef( "Transaction after begin in JdbcCoordinator @%s", hashCode() ); + JDBC_MESSAGE_LOGGER.transactionAfterBegin( hashCode() ); } owner.afterTransactionBegin(); } @@ -392,7 +389,7 @@ public void afterTransactionBegin() { @Override public void beforeTransactionCompletion() { if ( TRACE_ENABLED ) { - LOG.tracef( "Transaction before completion in JdbcCoordinator @%s", hashCode() ); + JDBC_MESSAGE_LOGGER.transactionBeforeCompletion( hashCode() ); } owner.beforeTransactionCompletion(); logicalConnection.beforeTransactionCompletion(); @@ -401,7 +398,7 @@ public void beforeTransactionCompletion() { @Override public void afterTransactionCompletion(boolean successful, boolean delayed) { if ( TRACE_ENABLED ) { - LOG.tracef( "Transaction after %s completion in JdbcCoordinator @%s", + JDBC_MESSAGE_LOGGER.transactionAfterCompletion( successful ? "successful" : "unsuccessful", hashCode() ); } diff --git a/hibernate-core/src/main/java/org/hibernate/internal/CoreMessageLogger.java b/hibernate-core/src/main/java/org/hibernate/internal/CoreMessageLogger.java index 767c776cfdff..df039f0a7770 100644 --- a/hibernate-core/src/main/java/org/hibernate/internal/CoreMessageLogger.java +++ b/hibernate-core/src/main/java/org/hibernate/internal/CoreMessageLogger.java @@ -78,27 +78,27 @@ public interface CoreMessageLogger extends BasicLogger { void callingJoinTransactionOnNonJtaEntityManager(); @LogMessage(level = DEBUG) - @Message(value = "Instantiating factory with settings: %s", id = 30) - void instantiatingFactory(Map settings); + @Message(value = "Instantiating factory [%s] with settings: %s", id = 30) + void instantiatingFactory(String uuid, Map settings); @LogMessage(level = DEBUG) - @Message(value = "Closing factory", id = 31) - void closingFactory(); + @Message(value = "Closing factory [%s]", id = 31) + void closingFactory(String uuid); @LogMessage(level = DEBUG) - @Message(value = "Serializing factory: %s", id = 32) + @Message(value = "Serializing factory [%s]", id = 32) void serializingFactory(String uuid); @LogMessage(level = DEBUG) - @Message(value = "Deserialized factory: %s", id = 33) + @Message(value = "Deserialized factory [%s]", id = 33) void deserializedFactory(String uuid); @LogMessage(level = WARN) - @Message(value = "Composite-id class does not override equals(): %s", id = 38) + @Message(value = "Composite id class does not override equals(): %s", id = 38) void compositeIdClassDoesNotOverrideEquals(String name); @LogMessage(level = WARN) - @Message(value = "Composite-id class does not override hashCode(): %s", id = 39) + @Message(value = "Composite id class does not override hashCode(): %s", id = 39) void compositeIdClassDoesNotOverrideHashCode(String name); @LogMessage(level = WARN) @@ -504,10 +504,6 @@ void missingArguments( @Message(value = "Write locks via update not supported for non-versioned entities [%s]", id = 416) void writeLocksNotSupported(String entityName); - @LogMessage(level = DEBUG) - @Message(value = "Closing unreleased batch", id = 420) - void closingUnreleasedBatch(); - @LogMessage(level = WARN) @Message( id = 437, diff --git a/hibernate-core/src/main/java/org/hibernate/internal/SessionFactoryImpl.java b/hibernate-core/src/main/java/org/hibernate/internal/SessionFactoryImpl.java index 2d0fa0eb0ba8..12326ee1939b 100644 --- a/hibernate-core/src/main/java/org/hibernate/internal/SessionFactoryImpl.java +++ b/hibernate-core/src/main/java/org/hibernate/internal/SessionFactoryImpl.java @@ -246,7 +246,7 @@ public SessionFactoryImpl( settings = getSettings( options, serviceRegistry ); maskOutSensitiveInformation( settings ); deprecationCheck( settings ); - LOG.instantiatingFactory( settings ); + LOG.instantiatingFactory( uuid, settings ); sqlStringGenerationContext = createSqlStringGenerationContext( bootMetamodel, options, jdbcServices ); @@ -814,7 +814,7 @@ public void close() { } try { - LOG.closingFactory(); + LOG.closingFactory( getUuid() ); observer.sessionFactoryClosing( this ); // NOTE : the null checks below handle cases where close is called from diff --git a/hibernate-core/src/main/java/org/hibernate/resource/jdbc/internal/LogicalConnectionManagedImpl.java b/hibernate-core/src/main/java/org/hibernate/resource/jdbc/internal/LogicalConnectionManagedImpl.java index 90c8fcf760c9..56705539606a 100644 --- a/hibernate-core/src/main/java/org/hibernate/resource/jdbc/internal/LogicalConnectionManagedImpl.java +++ b/hibernate-core/src/main/java/org/hibernate/resource/jdbc/internal/LogicalConnectionManagedImpl.java @@ -13,8 +13,6 @@ import org.hibernate.ResourceClosedException; import org.hibernate.engine.jdbc.connections.spi.JdbcConnectionAccess; import org.hibernate.engine.jdbc.spi.SqlExceptionHelper; -import org.hibernate.internal.CoreLogging; -import org.hibernate.internal.CoreMessageLogger; import org.hibernate.resource.jdbc.LogicalConnection; import org.hibernate.resource.jdbc.ResourceRegistry; import org.hibernate.resource.jdbc.spi.JdbcSessionContext; @@ -25,6 +23,7 @@ import static org.hibernate.ConnectionReleaseMode.AFTER_STATEMENT; import static org.hibernate.ConnectionReleaseMode.BEFORE_TRANSACTION_COMPLETION; import static org.hibernate.ConnectionReleaseMode.ON_CLOSE; +import static org.hibernate.engine.jdbc.JdbcLogging.JDBC_MESSAGE_LOGGER; import static org.hibernate.resource.jdbc.spi.PhysicalConnectionHandlingMode.DELAYED_ACQUISITION_AND_RELEASE_AFTER_TRANSACTION; /** @@ -36,7 +35,6 @@ * @author Steve Ebersole */ public class LogicalConnectionManagedImpl extends AbstractLogicalConnectionImplementor { - private static final CoreMessageLogger log = CoreLogging.messageLogger( LogicalConnectionManagedImpl.class ); private final transient JdbcSessionOwner jdbcSessionOwner; private final transient PhysicalConnectionHandlingMode connectionHandlingMode; @@ -55,7 +53,7 @@ public LogicalConnectionManagedImpl(JdbcSessionOwner sessionOwner, ResourceRegis } if ( sessionOwner.getJdbcSessionContext().doesConnectionProviderDisableAutoCommit() ) { - log.connectionProviderDisablesAutoCommitEnabled(); + JDBC_MESSAGE_LOGGER.connectionProviderDisablesAutoCommitEnabled(); } } @@ -133,10 +131,10 @@ public void afterStatement() { super.afterStatement(); if ( connectionHandlingMode.getReleaseMode() == AFTER_STATEMENT ) { if ( getResourceRegistry().hasRegisteredResources() ) { - log.trace( "Skipping aggressive JDBC connection release from 'afterStatement' due to held resources" ); + JDBC_MESSAGE_LOGGER.skipConnectionReleaseAfterStatementDueToResources( hashCode() ); } else { - log.trace( "Initiating JDBC connection release from 'afterStatement'" ); + JDBC_MESSAGE_LOGGER.initiatingConnectionReleaseAfterStatement( hashCode() ); releaseConnectionIfNeeded(); } } @@ -146,7 +144,7 @@ public void afterStatement() { public void beforeTransactionCompletion() { super.beforeTransactionCompletion(); if ( connectionHandlingMode.getReleaseMode() == BEFORE_TRANSACTION_COMPLETION ) { - log.trace( "Initiating JDBC connection release from 'beforeTransactionCompletion'" ); + JDBC_MESSAGE_LOGGER.initiatingConnectionReleaseBeforeTransactionCompletion( hashCode() ); releaseConnectionIfNeeded(); } } @@ -159,7 +157,7 @@ public void afterTransaction() { // - AFTER_STATEMENT cases that were circumvented due to held resources // - BEFORE_TRANSACTION_COMPLETION cases that were circumvented because a rollback occurred // (we don't get a beforeTransactionCompletion event on rollback). - log.trace( "Initiating JDBC connection release from 'afterTransaction'" ); + JDBC_MESSAGE_LOGGER.initiatingConnectionReleaseAfterTransaction( hashCode() ); releaseConnectionIfNeeded(); } } @@ -240,7 +238,7 @@ private void beforeRelease() { jdbcSessionOwner.beforeReleaseConnection( physicalConnection ); } catch (SQLException e) { - log.warn( "Error before releasing JDBC connection", e ); + JDBC_MESSAGE_LOGGER.errorBeforeReleasingJdbcConnection( hashCode(), e ); } } @@ -258,14 +256,14 @@ public static LogicalConnectionManagedImpl deserialize(ObjectInputStream ois, Jd public Connection close() { if ( !closed ) { getResourceRegistry().releaseResources(); - log.closingLogicalConnection(); + JDBC_MESSAGE_LOGGER.closingLogicalConnection( hashCode() ); try { releaseConnectionIfNeeded(); } finally { // no matter what closed = true; - log.logicalConnectionClosed(); + JDBC_MESSAGE_LOGGER.logicalConnectionClosed( hashCode() ); } } return null; From 5113f194887602c45269cf29e822075b301b7529 Mon Sep 17 00:00:00 2001 From: Gavin King Date: Sun, 13 Jul 2025 12:09:49 +0200 Subject: [PATCH 10/32] massive cleanup of NaturalIdResolutionsImpl --- .../internal/NaturalIdResolutionsImpl.java | 715 +++++++++--------- .../metamodel/mapping/NaturalIdLogging.java | 38 +- 2 files changed, 395 insertions(+), 358 deletions(-) diff --git a/hibernate-core/src/main/java/org/hibernate/engine/internal/NaturalIdResolutionsImpl.java b/hibernate-core/src/main/java/org/hibernate/engine/internal/NaturalIdResolutionsImpl.java index e6fd5f1f564f..b6ac0cfbd6b9 100644 --- a/hibernate-core/src/main/java/org/hibernate/engine/internal/NaturalIdResolutionsImpl.java +++ b/hibernate-core/src/main/java/org/hibernate/engine/internal/NaturalIdResolutionsImpl.java @@ -6,6 +6,7 @@ import java.io.Serializable; import java.util.ArrayList; +import java.util.Arrays; import java.util.Collection; import java.util.List; import java.util.Map; @@ -19,12 +20,10 @@ import org.hibernate.engine.spi.NaturalIdResolutions; import org.hibernate.engine.spi.PersistenceContext; import org.hibernate.engine.spi.Resolution; -import org.hibernate.engine.spi.SessionFactoryImplementor; import org.hibernate.engine.spi.SharedSessionContractImplementor; import org.hibernate.event.monitor.spi.EventMonitor; import org.hibernate.event.monitor.spi.DiagnosticEvent; import org.hibernate.metamodel.mapping.EntityMappingType; -import org.hibernate.metamodel.mapping.NaturalIdLogging; import org.hibernate.metamodel.mapping.NaturalIdMapping; import org.hibernate.persister.entity.EntityPersister; import org.hibernate.sql.results.LoadingLogger; @@ -33,6 +32,11 @@ import org.jboss.logging.Logger; +import static java.util.Collections.emptyList; +import static java.util.Collections.unmodifiableCollection; +import static org.hibernate.engine.internal.CacheHelper.fromSharedCache; +import static org.hibernate.metamodel.mapping.NaturalIdLogging.NATURAL_ID_MESSAGE_LOGGER; + public class NaturalIdResolutionsImpl implements NaturalIdResolutions, Serializable { private static final Logger LOG = Logger.getLogger( NaturalIdResolutionsImpl.class ); @@ -60,35 +64,28 @@ protected SharedSessionContractImplementor session() { @Override public boolean cacheResolution(Object id, Object naturalId, EntityMappingType entityDescriptor) { validateNaturalId( entityDescriptor, naturalId ); - return cacheResolutionLocally( id, naturalId, entityDescriptor ); } @Override public void cacheResolutionFromLoad(Object id, Object naturalId, EntityMappingType entityDescriptor) { - NaturalIdLogging.NATURAL_ID_LOGGER.tracef( - "Caching natural id resolution from load (%s) : '%s' -> '%s'", + NATURAL_ID_MESSAGE_LOGGER.cachingNaturalIdResolutionFromLoad( entityDescriptor.getEntityName(), - naturalId, + naturalId instanceof Object[] array ? Arrays.toString( array ) : naturalId, id ); - final EntityPersister persister = locatePersisterForKey( entityDescriptor.getEntityPersister() ); - final NaturalIdMapping naturalIdMapping = entityDescriptor.getNaturalIdMapping(); - if ( naturalIdMapping == null ) { - // nothing to do - return; - } - - // 'justAddedLocally' is meant to handle the case where we would get double stats journaling - // from a single load event. The first put journal would come from the natural id resolution; - // the second comes from the entity loading. In this condition, we want to avoid the multiple - // 'put' stats incrementing. - final boolean justAddedLocally = cacheResolution( id, naturalId, entityDescriptor ); - - if ( justAddedLocally && naturalIdMapping.getCacheAccess() != null ) { - manageSharedResolution( persister, id, naturalId, (Object) null, CachedNaturalIdValueSource.LOAD ); + if ( naturalIdMapping != null ) { + // 'justAddedLocally' is meant to handle the case where we would get double stats journaling + // from a single load event. The first put journal would come from the natural id resolution; + // the second comes from the entity loading. In this condition, we want to avoid the multiple + // 'put' stats incrementing. + final boolean justAddedLocally = cacheResolution( id, naturalId, entityDescriptor ); + if ( justAddedLocally && naturalIdMapping.getCacheAccess() != null ) { + final EntityPersister persister = locatePersisterForKey( entityDescriptor.getEntityPersister() ); + manageSharedResolution( persister, id, naturalId, (Object) null, CachedNaturalIdValueSource.LOAD ); + } } } @@ -96,14 +93,13 @@ public void cacheResolutionFromLoad(Object id, Object naturalId, EntityMappingTy * Private, but see {@link #cacheResolution} for public version */ private boolean cacheResolutionLocally(Object id, Object naturalId, EntityMappingType entityDescriptor) { - // by the time we get here we assume that the natural-id value has already been validated so just do an assert + // by the time we get here, we assume that the natural id value has already been validated, so just assert assert entityDescriptor.getNaturalIdMapping() != null; assert isValidValue( naturalId, entityDescriptor ); - NaturalIdLogging.NATURAL_ID_LOGGER.tracef( - "Locally caching natural id resolution (%s) : '%s' -> '%s'", + NATURAL_ID_MESSAGE_LOGGER.locallyCachingNaturalIdResolution( entityDescriptor.getEntityName(), - naturalId, + naturalId instanceof Object[] array ? Arrays.toString( array ) : naturalId, id ); @@ -125,7 +121,7 @@ private boolean cacheResolutionLocally(Object id, Object naturalId, EntityMappin public Object removeResolution(Object id, Object naturalId, EntityMappingType entityDescriptor) { final EntityPersister persister = locatePersisterForKey( entityDescriptor.getEntityPersister() ); - final NaturalIdMapping naturalIdMapping = persister.getNaturalIdMapping(); +// final NaturalIdMapping naturalIdMapping = persister.getNaturalIdMapping(); validateNaturalId( persister, naturalId ); final EntityResolutions entityNaturalIdResolutionCache = resolutionsByEntity.get( persister ); @@ -159,29 +155,21 @@ public void manageLocalResolution( @Override public Object removeLocalResolution(Object id, Object naturalId, EntityMappingType entityDescriptor) { - NaturalIdLogging.NATURAL_ID_LOGGER.tracef( - "Removing locally cached natural id resolution (%s) : '%s' -> '%s'", - entityDescriptor.getEntityName(), - naturalId, - id - ); - final NaturalIdMapping naturalIdMapping = entityDescriptor.getNaturalIdMapping(); + if ( naturalIdMapping != null ) { + NATURAL_ID_MESSAGE_LOGGER.removingLocallyCachedNaturalIdResolution( + entityDescriptor.getEntityName(), + naturalId instanceof Object[] array ? Arrays.toString( array ) : naturalId, + id + ); - if ( naturalIdMapping == null ) { - // nothing to do + final EntityPersister persister = locatePersisterForKey( entityDescriptor.getEntityPersister() ); + final Object localNaturalIdValues = removeNaturalIdCrossReference( id, naturalId, persister ); + return localNaturalIdValues == null ? naturalId : localNaturalIdValues; + } + else { return null; } - - final EntityPersister persister = locatePersisterForKey( entityDescriptor.getEntityPersister() ); - - final Object localNaturalIdValues = removeNaturalIdCrossReference( - id, - naturalId, - persister - ); - - return localNaturalIdValues != null ? localNaturalIdValues : naturalId; } /** @@ -189,33 +177,39 @@ public Object removeLocalResolution(Object id, Object naturalId, EntityMappingTy * second-level cache (NaturalIdDataAccess). Returns the natural-id value previously * cached on the Session */ - private Object removeNaturalIdCrossReference(Object id, Object naturalIdValue, EntityPersister persister) { - validateNaturalId( persister, naturalIdValue ); + private Object removeNaturalIdCrossReference(Object id, Object naturalId, EntityPersister persister) { + validateNaturalId( persister, naturalId ); + final Object sessionCachedNaturalId = removeSessionCachedNaturalIdValue( id, persister ); + if ( persister.hasNaturalIdCache() ) { + final SharedSessionContractImplementor session = session(); + evictCachedNaturalId( naturalId, persister, session ); + if ( sessionCachedNaturalId != null + // TODO: we should not really use equals() to compare instances of Hibernate Types + && !Objects.deepEquals( sessionCachedNaturalId, naturalId ) ) { + evictCachedNaturalId( sessionCachedNaturalId, persister, session ); + } + } + return sessionCachedNaturalId; + } - final EntityResolutions entityResolutions = this.resolutionsByEntity.get( persister ); - Object sessionCachedNaturalIdValues = null; + private static void evictCachedNaturalId( + Object naturalId, + EntityPersister persister, + SharedSessionContractImplementor session) { + final NaturalIdDataAccess cacheAccessStrategy = persister.getNaturalIdCacheAccessStrategy(); + cacheAccessStrategy.evict( cacheAccessStrategy.generateCacheKey( naturalId, persister, session ) ); + } + + private Object removeSessionCachedNaturalIdValue(Object id, EntityPersister persister) { + final EntityResolutions entityResolutions = resolutionsByEntity.get( persister ); if ( entityResolutions != null ) { final Resolution cachedNaturalId = entityResolutions.pkToNaturalIdMap.remove( id ); if ( cachedNaturalId != null ) { entityResolutions.naturalIdToPkMap.remove( cachedNaturalId ); - sessionCachedNaturalIdValues = cachedNaturalId.getNaturalIdValue(); - } - } - - if ( persister.hasNaturalIdCache() ) { - final NaturalIdDataAccess naturalIdCacheAccessStrategy = persister - .getNaturalIdCacheAccessStrategy(); - final Object naturalIdCacheKey = naturalIdCacheAccessStrategy.generateCacheKey( naturalIdValue, persister, session() ); - naturalIdCacheAccessStrategy.evict( naturalIdCacheKey ); - - if ( sessionCachedNaturalIdValues != null - && ! Objects.deepEquals( sessionCachedNaturalIdValues, naturalIdValue ) ) { - final Object sessionNaturalIdCacheKey = naturalIdCacheAccessStrategy.generateCacheKey( sessionCachedNaturalIdValues, persister, session() ); - naturalIdCacheAccessStrategy.evict( sessionNaturalIdCacheKey ); + return cachedNaturalId.getNaturalIdValue(); } } - - return sessionCachedNaturalIdValues; + return null; } @Override @@ -226,24 +220,15 @@ public void manageSharedResolution( EntityMappingType entityDescriptor, CachedNaturalIdValueSource source) { final NaturalIdMapping naturalIdMapping = entityDescriptor.getNaturalIdMapping(); - - if ( naturalIdMapping == null ) { - // nothing to do - return; - } - - if ( naturalIdMapping.getCacheAccess() == null ) { - // nothing to do - return; + if ( naturalIdMapping != null && naturalIdMapping.getCacheAccess() != null ) { + manageSharedResolution( + entityDescriptor.getEntityPersister(), + id, + naturalId, + previousNaturalId, + source + ); } - - manageSharedResolution( - entityDescriptor.getEntityPersister(), - id, - naturalId, - previousNaturalId, - source - ); } private void manageSharedResolution( @@ -253,180 +238,217 @@ private void manageSharedResolution( Object previousNaturalIdValues, CachedNaturalIdValueSource source) { final NaturalIdDataAccess cacheAccess = persister.getNaturalIdMapping().getCacheAccess(); - - if ( cacheAccess == null ) { - return; - } - final SharedSessionContractImplementor s = session(); - final EntityMappingType rootEntityDescriptor = persister.getRootEntityDescriptor(); - final EntityPersister rootEntityPersister = rootEntityDescriptor.getEntityPersister(); - - final Object cacheKey = cacheAccess.generateCacheKey( naturalIdValues, rootEntityPersister, s ); - - final SessionFactoryImplementor factory = s.getFactory(); - final StatisticsImplementor statistics = factory.getStatistics(); - final EventMonitor eventMonitor = s.getEventMonitor(); - switch ( source ) { - case LOAD: { - if ( CacheHelper.fromSharedCache( s, cacheKey, persister, cacheAccess ) != null ) { - // prevent identical re-cachings - return; - } - boolean put = false; - final DiagnosticEvent cachePutEvent = eventMonitor.beginCachePutEvent(); - try { - put = cacheAccess.putFromLoad( - s, + if ( cacheAccess != null ) { + final EntityMappingType rootEntityDescriptor = persister.getRootEntityDescriptor(); + final EntityPersister rootEntityPersister = rootEntityDescriptor.getEntityPersister(); + final Object cacheKey = cacheAccess.generateCacheKey( naturalIdValues, rootEntityPersister, session() ); + switch ( source ) { + case LOAD: + cacheFromLoad( + persister, + id, cacheKey, + cacheAccess, + rootEntityDescriptor, + rootEntityPersister + ); + break; + case INSERT: + cacheFromInsert( id, - null + cacheAccess, + cacheKey, + rootEntityDescriptor, + rootEntityPersister ); - - if ( put && statistics.isStatisticsEnabled() ) { - statistics.naturalIdCachePut( - rootEntityDescriptor.getNavigableRole(), - cacheAccess.getRegion().getName() - ); - } - } - finally { - eventMonitor.completeCachePutEvent( - cachePutEvent, - session(), + break; + case UPDATE: + cacheFromUpdate( + id, + previousNaturalIdValues, cacheAccess, rootEntityPersister, - put, - true, - EventMonitor.CacheActionDescription.ENTITY_LOAD + cacheKey, + rootEntityDescriptor ); - } - break; - } - case INSERT: { - boolean put = false; - final DiagnosticEvent cachePutEvent = eventMonitor.beginCachePutEvent(); - - try { - put = cacheAccess.insert( s, cacheKey, id ); - if ( put && statistics.isStatisticsEnabled() ) { - statistics.naturalIdCachePut( - rootEntityDescriptor.getNavigableRole(), - cacheAccess.getRegion().getName() - ); + break; + default: + if ( LOG.isDebugEnabled() ) { + LOG.debug( "Unexpected CachedNaturalIdValueSource [" + source + "]" ); } - } - finally { - eventMonitor.completeCachePutEvent( - cachePutEvent, - session(), - cacheAccess, - rootEntityPersister, - put, - true, - EventMonitor.CacheActionDescription.ENTITY_INSERT - ); - } + } + } + } - s.asEventSource().getActionQueue().registerProcess( - (success, session) -> { - if ( success ) { - final boolean put1 = cacheAccess.afterInsert( session, cacheKey, id ); - if ( put1 && statistics.isStatisticsEnabled() ) { - statistics.naturalIdCachePut( - rootEntityDescriptor.getNavigableRole(), - cacheAccess.getRegion().getName() - ); - } - } - else { - cacheAccess.evict( cacheKey ); - } - } - ); + private void cacheFromUpdate( + Object id, + Object previousNaturalIdValues, + NaturalIdDataAccess cacheAccess, + EntityPersister rootEntityPersister, + Object cacheKey, + EntityMappingType rootEntityDescriptor) { + final SharedSessionContractImplementor session = session(); - break; + final Object previousCacheKey = + cacheAccess.generateCacheKey( previousNaturalIdValues, rootEntityPersister, session ); + if ( cacheKey.equals( previousCacheKey ) ) { + // prevent identical re-caching, solves HHH-7309 + return; + } + + final SoftLock removalLock = cacheAccess.lockItem( session, previousCacheKey, null ); + cacheAccess.remove( session, previousCacheKey); + final SoftLock lock = cacheAccess.lockItem( session, cacheKey, null ); + + final StatisticsImplementor statistics = session.getFactory().getStatistics(); + final EventMonitor eventMonitor = session.getEventMonitor(); + boolean put = false; + final DiagnosticEvent cachePutEvent = eventMonitor.beginCachePutEvent(); + try { + put = cacheAccess.update( session, cacheKey, id ); + if ( put && statistics.isStatisticsEnabled() ) { + statistics.naturalIdCachePut( + rootEntityDescriptor.getNavigableRole(), + cacheAccess.getRegion().getName() + ); } - case UPDATE: { - final Object previousCacheKey = cacheAccess.generateCacheKey( previousNaturalIdValues, rootEntityPersister, s ); - if ( cacheKey.equals( previousCacheKey ) ) { - // prevent identical re-caching, solves HHH-7309 - return; - } - final SoftLock removalLock = cacheAccess.lockItem( s, previousCacheKey, null ); - cacheAccess.remove( s, previousCacheKey); - - final SoftLock lock = cacheAccess.lockItem( s, cacheKey, null ); - boolean put = false; - final DiagnosticEvent cachePutEvent = eventMonitor.beginCachePutEvent(); - try { - put = cacheAccess.update( s, cacheKey, id ); - if ( put && statistics.isStatisticsEnabled() ) { - statistics.naturalIdCachePut( - rootEntityDescriptor.getNavigableRole(), - cacheAccess.getRegion().getName() - ); - } - } - finally { - eventMonitor.completeCachePutEvent( - cachePutEvent, - session(), - cacheAccess, - rootEntityPersister, - put, - true, - EventMonitor.CacheActionDescription.ENTITY_UPDATE - ); - } + } + finally { + eventMonitor.completeCachePutEvent( + cachePutEvent, + session(), + cacheAccess, + rootEntityPersister, + put, + true, + EventMonitor.CacheActionDescription.ENTITY_UPDATE + ); + } - s.asEventSource().getActionQueue().registerProcess( - (success, session) -> { - cacheAccess.unlockItem( s, previousCacheKey, removalLock ); - if (success) { - boolean putAfterUpdate = false; - final DiagnosticEvent cachePutEventAfterUpdate = eventMonitor.beginCachePutEvent(); - try { - putAfterUpdate = cacheAccess.afterUpdate( - s, - cacheKey, - id, - lock - ); - - if ( putAfterUpdate && statistics.isStatisticsEnabled() ) { - statistics.naturalIdCachePut( - rootEntityDescriptor.getNavigableRole(), - cacheAccess.getRegion().getName() - ); - } - } - finally { - eventMonitor.completeCachePutEvent( - cachePutEventAfterUpdate, - session(), - cacheAccess, - rootEntityPersister, - putAfterUpdate, - true, - EventMonitor.CacheActionDescription.ENTITY_AFTER_UPDATE - ); - } - } - else { - cacheAccess.unlockItem( s, cacheKey, lock ); + session.asEventSource().getActionQueue().registerProcess( + (success, sess) -> { + cacheAccess.unlockItem( sess, previousCacheKey, removalLock ); + if (success) { + boolean putAfterUpdate = false; + final DiagnosticEvent cachePutEventAfterUpdate = eventMonitor.beginCachePutEvent(); + try { + putAfterUpdate = cacheAccess.afterUpdate( sess, cacheKey, id, lock ); + if ( putAfterUpdate && statistics.isStatisticsEnabled() ) { + statistics.naturalIdCachePut( + rootEntityDescriptor.getNavigableRole(), + cacheAccess.getRegion().getName() + ); } } - ); + finally { + eventMonitor.completeCachePutEvent( + cachePutEventAfterUpdate, + session(), + cacheAccess, + rootEntityPersister, + putAfterUpdate, + true, + EventMonitor.CacheActionDescription.ENTITY_AFTER_UPDATE + ); + } + } + else { + cacheAccess.unlockItem( sess, cacheKey, lock ); + } + } + ); + } + + private void cacheFromInsert( + Object id, + NaturalIdDataAccess cacheAccess, + Object cacheKey, + EntityMappingType rootEntityDescriptor, + EntityPersister rootEntityPersister) { + final SharedSessionContractImplementor session = session(); - break; + final StatisticsImplementor statistics = session.getFactory().getStatistics(); + final EventMonitor eventMonitor = session.getEventMonitor(); + boolean put = false; + final DiagnosticEvent cachePutEvent = eventMonitor.beginCachePutEvent(); + try { + put = cacheAccess.insert( session, cacheKey, id ); + if ( put && statistics.isStatisticsEnabled() ) { + statistics.naturalIdCachePut( + rootEntityDescriptor.getNavigableRole(), + cacheAccess.getRegion().getName() + ); } - default: { - if ( LOG.isDebugEnabled() ) { - LOG.debug( "Unexpected CachedNaturalIdValueSource [" + source + "]" ); + } + finally { + eventMonitor.completeCachePutEvent( + cachePutEvent, + session(), + cacheAccess, + rootEntityPersister, + put, + true, + EventMonitor.CacheActionDescription.ENTITY_INSERT + ); + } + + session.asEventSource().getActionQueue().registerProcess( + (success, sess) -> { + if ( success ) { + final boolean changed = cacheAccess.afterInsert( sess, cacheKey, id ); + if ( changed && statistics.isStatisticsEnabled() ) { + statistics.naturalIdCachePut( + rootEntityDescriptor.getNavigableRole(), + cacheAccess.getRegion().getName() + ); + } + } + else { + cacheAccess.evict( cacheKey ); + } } + ); + } + + private void cacheFromLoad( + EntityPersister persister, + Object id, + Object cacheKey, + NaturalIdDataAccess cacheAccess, + EntityMappingType rootEntityDescriptor, + EntityPersister rootEntityPersister) { + final SharedSessionContractImplementor session = session(); + + if ( fromSharedCache( session, cacheKey, persister, cacheAccess ) != null ) { + // prevent identical re-caching + return; + } + + final StatisticsImplementor statistics = session.getFactory().getStatistics(); + final EventMonitor eventMonitor = session.getEventMonitor(); + boolean put = false; + final DiagnosticEvent cachePutEvent = eventMonitor.beginCachePutEvent(); + try { + put = cacheAccess.putFromLoad( session, cacheKey, id, null ); + if ( put && statistics.isStatisticsEnabled() ) { + statistics.naturalIdCachePut( + rootEntityDescriptor.getNavigableRole(), + cacheAccess.getRegion().getName() + ); } } + finally { + eventMonitor.completeCachePutEvent( + cachePutEvent, + session, + cacheAccess, + rootEntityPersister, + put, + true, + EventMonitor.CacheActionDescription.ENTITY_LOAD + ); + } } @Override @@ -453,12 +475,12 @@ public void removeSharedResolution(Object id, Object naturalId, EntityMappingTyp // 1) should be using access strategy, not plain evict.. // 2) should prefer session-cached values if any (requires interaction from removeLocalNaturalIdCrossReference) + final SharedSessionContractImplementor session = session(); final EntityPersister persister = locatePersisterForKey( entityDescriptor.getEntityPersister() ); - - final Object naturalIdCacheKey = cacheAccess.generateCacheKey( naturalId, persister, session() ); + final Object naturalIdCacheKey = cacheAccess.generateCacheKey( naturalId, persister, session ); if ( delayToAfterTransactionCompletion ) { - session().asEventSource().getActionQueue().registerProcess( - (success, session) -> { + session.asEventSource().getActionQueue().registerProcess( + (success, sess) -> { if ( success ) { cacheAccess.evict( naturalIdCacheKey ); } @@ -479,21 +501,16 @@ public void removeSharedResolution(Object id, Object naturalId, EntityMappingTyp @Override public void handleSynchronization(Object pk, Object entity, EntityMappingType entityDescriptor) { final NaturalIdMapping naturalIdMapping = entityDescriptor.getNaturalIdMapping(); - if ( naturalIdMapping == null ) { - // nothing to do - return; - } - final EntityPersister persister = locatePersisterForKey( entityDescriptor.getEntityPersister() ); - - final Object naturalIdValuesFromCurrentObjectState = naturalIdMapping.extractNaturalIdFromEntity( entity ); - final boolean changed = !sameAsCached( persister, pk, naturalIdValuesFromCurrentObjectState ); - - if ( changed ) { - final Object cachedNaturalIdValues = findCachedNaturalIdById( pk, persister ); - cacheResolution( pk, naturalIdValuesFromCurrentObjectState, persister ); - stashInvalidNaturalIdReference( persister, cachedNaturalIdValues ); - - removeSharedResolution( pk, cachedNaturalIdValues, persister, false ); + if ( naturalIdMapping != null ) { + final EntityPersister persister = locatePersisterForKey( entityDescriptor.getEntityPersister() ); + final Object naturalIdValuesFromCurrentObjectState = naturalIdMapping.extractNaturalIdFromEntity( entity ); + final boolean changed = !sameAsCached( persister, pk, naturalIdValuesFromCurrentObjectState ); + if ( changed ) { + final Object cachedNaturalIdValues = findCachedNaturalIdById( pk, persister ); + cacheResolution( pk, naturalIdValuesFromCurrentObjectState, persister ); + stashInvalidNaturalIdReference( persister, cachedNaturalIdValues ); + removeSharedResolution( pk, cachedNaturalIdValues, persister, false ); + } } } @@ -504,11 +521,7 @@ public void cleanupFromSynchronizations() { @Override public void handleEviction(Object id, Object object, EntityMappingType entityDescriptor) { - removeResolution( - id, - findCachedNaturalIdById( id, entityDescriptor ), - entityDescriptor - ); + removeResolution( id, findCachedNaturalIdById( id, entityDescriptor ), entityDescriptor ); } /** @@ -523,7 +536,7 @@ public void handleEviction(Object id, Object object, EntityMappingType entityDes public boolean sameAsCached(EntityPersister persister, Object pk, Object naturalIdValues) { final EntityResolutions entityNaturalIdResolutionCache = resolutionsByEntity.get( persister ); return entityNaturalIdResolutionCache != null - && entityNaturalIdResolutionCache.sameAsCached( pk, naturalIdValues ); + && entityNaturalIdResolutionCache.sameAsCached( pk, naturalIdValues ); } /** @@ -549,23 +562,18 @@ protected EntityPersister locatePersisterForKey(EntityPersister persister) { */ protected void validateNaturalId(EntityMappingType entityDescriptor, Object naturalIdValues) { final NaturalIdMapping naturalIdMapping = entityDescriptor.getNaturalIdMapping(); - if ( naturalIdMapping == null ) { - throw new IllegalArgumentException( "Entity did not define a natural-id" ); + throw new IllegalArgumentException( "Entity did not define a natural id" ); } - naturalIdMapping.validateInternalForm( naturalIdValues ); } private boolean isValidValue(Object naturalIdValues, EntityMappingType entityDescriptor) { final NaturalIdMapping naturalIdMapping = entityDescriptor.getNaturalIdMapping(); - if ( naturalIdMapping == null ) { - throw new IllegalArgumentException( "Entity did not define a natural-id" ); + throw new IllegalArgumentException( "Entity did not define a natural id" ); } - naturalIdMapping.validateInternalForm( naturalIdValues ); - // validateInternalForm would have thrown an exception if not return true; } @@ -585,13 +593,15 @@ public Object findCachedNaturalIdById(Object id, EntityMappingType entityDescrip if ( entityNaturalIdResolutionCache == null ) { return null; } - - final Resolution cachedNaturalId = entityNaturalIdResolutionCache.pkToNaturalIdMap.get( id ); - if ( cachedNaturalId == null ) { - return null; + else { + final Resolution cachedNaturalId = entityNaturalIdResolutionCache.pkToNaturalIdMap.get( id ); + if ( cachedNaturalId == null ) { + return null; + } + else { + return cachedNaturalId.getNaturalIdValue(); + } } - - return cachedNaturalId.getNaturalIdValue(); } @Override @@ -607,30 +617,24 @@ public Object findCachedIdByNaturalId(Object naturalId, EntityMappingType entity final EntityPersister persister = locatePersisterForKey( entityDescriptor.getEntityPersister() ); validateNaturalId( persister, naturalId ); - EntityResolutions entityNaturalIdResolutionCache = resolutionsByEntity.get( persister ); + final EntityResolutions resolutionCache = resolutionsByEntity.get( persister ); - Object pk; final Resolution cachedNaturalId = new ResolutionImpl( persister, naturalId, persistenceContext ); - if ( entityNaturalIdResolutionCache != null ) { - pk = entityNaturalIdResolutionCache.naturalIdToPkMap.get( cachedNaturalId ); - - // Found in session cache - if ( pk != null ) { - if ( LOG.isTraceEnabled() ) { - LOG.tracef( - "Resolved natural key (%s) -> primary key (%s) resolution in session cache for `%s`:", - naturalId, - pk, - entityDescriptor.getEntityName() - ); + if ( resolutionCache != null ) { + // Try the session cache + final Object identifier = resolutionCache.naturalIdToPkMap.get( cachedNaturalId ); + if ( identifier != null ) { + // Found in session cache + if ( NATURAL_ID_MESSAGE_LOGGER.isTraceEnabled() ) { + NATURAL_ID_MESSAGE_LOGGER.resolvedNaturalIdInSessionCache( naturalId, identifier, + entityDescriptor.getEntityName() ); } - - return pk; + return identifier; } - // if we did not find a hit, see if we know about these natural ids as invalid... - if ( entityNaturalIdResolutionCache.containsInvalidNaturalIdReference( naturalId ) ) { - return NaturalIdResolutions.INVALID_NATURAL_ID_REFERENCE; + // if we did not find a hit, see if we know about these natural ids as invalid + if ( resolutionCache.containsInvalidNaturalIdReference( naturalId ) ) { + return INVALID_NATURAL_ID_REFERENCE; } } @@ -638,73 +642,72 @@ public Object findCachedIdByNaturalId(Object naturalId, EntityMappingType entity if ( !persister.hasNaturalIdCache() ) { return null; } - - // Try resolution from second-level cache - final NaturalIdDataAccess naturalIdCacheAccessStrategy = persister.getNaturalIdCacheAccessStrategy(); - final SharedSessionContractImplementor session = session(); - final Object naturalIdCacheKey = naturalIdCacheAccessStrategy.generateCacheKey( naturalId, persister, session ); - - pk = CacheHelper.fromSharedCache( session, naturalIdCacheKey, persister, true, naturalIdCacheAccessStrategy ); - - // Found in second-level cache, store in session cache - final SessionFactoryImplementor factory = session.getFactory(); - final StatisticsImplementor statistics = factory.getStatistics(); - final boolean statisticsEnabled = statistics.isStatisticsEnabled(); - if ( pk != null ) { - if ( statisticsEnabled ) { - statistics.naturalIdCacheHit( - StatsHelper.getRootEntityRole( persister ), - naturalIdCacheAccessStrategy.getRegion().getName() - ); - } - - if ( LOG.isTraceEnabled() ) { - // protected to avoid Arrays.toString call unless needed - LOG.tracef( - "Found natural key [%s] -> primary key [%s] xref in second-level cache for %s", - naturalId, - pk, - persister.getRootEntityName() - ); + else { + // Try the second-level cache + final NaturalIdDataAccess cacheAccessStrategy = persister.getNaturalIdCacheAccessStrategy(); + final SharedSessionContractImplementor session = session(); + final Object cacheKey = cacheAccessStrategy.generateCacheKey( naturalId, persister, session ); + final Object id = fromSharedCache( session, cacheKey, persister, true, cacheAccessStrategy ); + final StatisticsImplementor statistics = session.getFactory().getStatistics(); + final boolean statisticsEnabled = statistics.isStatisticsEnabled(); + if ( id != null ) { + // Found in second-level cache, store in session cache + if ( statisticsEnabled ) { + statistics.naturalIdCacheHit( + StatsHelper.getRootEntityRole( persister ), + cacheAccessStrategy.getRegion().getName() + ); + } + if ( NATURAL_ID_MESSAGE_LOGGER.isTraceEnabled() ) { + // protected to avoid Arrays.toString call unless needed + NATURAL_ID_MESSAGE_LOGGER.foundNaturalIdInSecondLevelCache( naturalId, id, + persister.getRootEntityName() ); + } + storeInResolutionCache( resolutionCache, persister, id, cachedNaturalId ); + return id; } - - if ( entityNaturalIdResolutionCache == null ) { - entityNaturalIdResolutionCache = new EntityResolutions( persister, persistenceContext ); - EntityResolutions existingCache = resolutionsByEntity.putIfAbsent( persister, entityNaturalIdResolutionCache ); - if ( existingCache != null ) { - entityNaturalIdResolutionCache = existingCache; + else { + // Not found anywhere + if ( statisticsEnabled ) { + statistics.naturalIdCacheMiss( + StatsHelper.getRootEntityRole( persister ), + cacheAccessStrategy.getRegion().getName() + ); } + return null; } - - entityNaturalIdResolutionCache.pkToNaturalIdMap.put( pk, cachedNaturalId ); - entityNaturalIdResolutionCache.naturalIdToPkMap.put( cachedNaturalId, pk ); } - else if ( statisticsEnabled ) { - statistics.naturalIdCacheMiss( - StatsHelper.getRootEntityRole( persister ), - naturalIdCacheAccessStrategy.getRegion().getName() - ); + } + + private void storeInResolutionCache( + EntityResolutions resolutionCache, + EntityPersister persister, + Object pk, + Resolution cachedNaturalId) { + + if ( resolutionCache == null ) { + resolutionCache = new EntityResolutions( persister, persistenceContext ); + final EntityResolutions existingCache = + resolutionsByEntity.putIfAbsent( persister, resolutionCache ); + if ( existingCache != null ) { + resolutionCache = existingCache; + } } - return pk; + resolutionCache.pkToNaturalIdMap.put( pk, cachedNaturalId ); + resolutionCache.naturalIdToPkMap.put( cachedNaturalId, pk ); } @Override public Collection getCachedPkResolutions(EntityMappingType entityDescriptor) { final EntityPersister persister = locatePersisterForKey( entityDescriptor.getEntityPersister() ); - - Collection pks = null; - final EntityResolutions entityNaturalIdResolutionCache = resolutionsByEntity.get( persister ); if ( entityNaturalIdResolutionCache != null ) { - pks = entityNaturalIdResolutionCache.pkToNaturalIdMap.keySet(); - } - - if ( pks == null || pks.isEmpty() ) { - return java.util.Collections.emptyList(); + final Collection pks = entityNaturalIdResolutionCache.pkToNaturalIdMap.keySet(); + return pks.isEmpty() ? emptyList() : unmodifiableCollection( pks ); } else { - return java.util.Collections.unmodifiableCollection( pks ); + return emptyList(); } } @@ -720,12 +723,11 @@ public Collection getCachedPkResolutions(EntityMappingType entityDescriptor) */ public void stashInvalidNaturalIdReference(EntityPersister persister, Object invalidNaturalIdValues) { persister = locatePersisterForKey( persister ); - final EntityResolutions entityNaturalIdResolutionCache = resolutionsByEntity.get( persister ); if ( entityNaturalIdResolutionCache == null ) { - throw new AssertionFailure( "Expecting NaturalIdResolutionCache to exist already for entity " + persister.getEntityName() ); + throw new AssertionFailure( "Expecting NaturalIdResolutionCache to exist already for entity " + + persister.getEntityName() ); } - entityNaturalIdResolutionCache.stashInvalidNaturalIdReference( invalidNaturalIdValues ); } @@ -808,7 +810,7 @@ public void stashInvalidNaturalIdReference(Object invalidNaturalIdValues) { public boolean containsInvalidNaturalIdReference(Object naturalIdValues) { return invalidNaturalIdList != null - && invalidNaturalIdList.contains( new ResolutionImpl( getEntityDescriptor(), naturalIdValues, persistenceContext ) ); + && invalidNaturalIdList.contains( new ResolutionImpl( getEntityDescriptor(), naturalIdValues, persistenceContext ) ); } public void unStashInvalidNaturalIdReferences() { @@ -855,20 +857,19 @@ public boolean equals(Object obj) { if ( this == obj ) { return true; } - if ( obj == null ) { + else if ( !(obj instanceof ResolutionImpl other) ) { return false; } - if ( getClass() != obj.getClass() ) { - return false; + else { + return entityDescriptor.equals( other.entityDescriptor ) + && isSame( other.naturalIdValue ); } - - final ResolutionImpl other = (ResolutionImpl) obj; - return entityDescriptor.equals( other.entityDescriptor ) && isSame( other.naturalIdValue ); } @Override public boolean isSame(Object otherValue) { - return entityDescriptor.getNaturalIdMapping().areEqual( naturalIdValue, otherValue, persistenceContext.getSession() ); + return entityDescriptor.getNaturalIdMapping() + .areEqual( naturalIdValue, otherValue, persistenceContext.getSession() ); } } } diff --git a/hibernate-core/src/main/java/org/hibernate/metamodel/mapping/NaturalIdLogging.java b/hibernate-core/src/main/java/org/hibernate/metamodel/mapping/NaturalIdLogging.java index a1bfcf37c094..da15831d819b 100644 --- a/hibernate-core/src/main/java/org/hibernate/metamodel/mapping/NaturalIdLogging.java +++ b/hibernate-core/src/main/java/org/hibernate/metamodel/mapping/NaturalIdLogging.java @@ -7,7 +7,16 @@ import org.hibernate.Internal; import org.hibernate.internal.log.SubSystemLogging; +import org.jboss.logging.BasicLogger; import org.jboss.logging.Logger; +import org.jboss.logging.annotations.LogMessage; +import org.jboss.logging.annotations.Message; +import org.jboss.logging.annotations.MessageLogger; +import org.jboss.logging.annotations.ValidIdRange; + +import java.lang.invoke.MethodHandles; + +import static org.jboss.logging.Logger.Level.TRACE; /** * Logging related to natural-id operations @@ -18,8 +27,35 @@ name = NaturalIdLogging.LOGGER_NAME, description = "Logging related to handling of natural-id mappings" ) +@MessageLogger(projectCode = "HHH") +@ValidIdRange(min = 90001, max = 90100) @Internal -public interface NaturalIdLogging { +public interface NaturalIdLogging extends BasicLogger { String LOGGER_NAME = SubSystemLogging.BASE + ".mapping.natural_id"; Logger NATURAL_ID_LOGGER = Logger.getLogger( LOGGER_NAME ); + NaturalIdLogging NATURAL_ID_MESSAGE_LOGGER = Logger.getMessageLogger( + MethodHandles.lookup(), + NaturalIdLogging.class, + LOGGER_NAME + ); + + @LogMessage(level = TRACE) + @Message(value = "Caching natural id resolution from load [%s] : %s -> %s", id = 90001) + void cachingNaturalIdResolutionFromLoad(String entityName, Object naturalId, Object id); + + @LogMessage(level = TRACE) + @Message(value = "Locally caching natural id resolution [%s] : %s -> %s", id = 90002) + void locallyCachingNaturalIdResolution(String entityName, Object naturalId, Object id); + + @LogMessage(level = TRACE) + @Message(value = "Removing locally cached natural id resolution [%s] : %s -> %s", id = 90003) + void removingLocallyCachedNaturalIdResolution(String entityName, Object naturalId, Object id); + + @LogMessage(level = TRACE) + @Message(value = "Resolved natural key [%s] -> primary key [%s] resolution in session cache for [%s]:", id = 90004) + void resolvedNaturalIdInSessionCache(Object naturalId, Object pk, String entityName); + + @LogMessage(level = TRACE) + @Message(value = "Found natural key [%s] -> primary key [%s] xref in second-level cache for [%s]", id = 90005) + void foundNaturalIdInSecondLevelCache(Object naturalId, Object pk, String entityName); } From 7d2fc89b16e388d15177899707d042488a330f58 Mon Sep 17 00:00:00 2001 From: Gavin King Date: Sun, 13 Jul 2025 12:12:35 +0200 Subject: [PATCH 11/32] move NaturalIdLogging to package with its only client --- .../mapping => engine/internal}/NaturalIdLogging.java | 4 ++-- .../hibernate/engine/internal/NaturalIdResolutionsImpl.java | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) rename hibernate-core/src/main/java/org/hibernate/{metamodel/mapping => engine/internal}/NaturalIdLogging.java (95%) diff --git a/hibernate-core/src/main/java/org/hibernate/metamodel/mapping/NaturalIdLogging.java b/hibernate-core/src/main/java/org/hibernate/engine/internal/NaturalIdLogging.java similarity index 95% rename from hibernate-core/src/main/java/org/hibernate/metamodel/mapping/NaturalIdLogging.java rename to hibernate-core/src/main/java/org/hibernate/engine/internal/NaturalIdLogging.java index da15831d819b..80cff5cc8246 100644 --- a/hibernate-core/src/main/java/org/hibernate/metamodel/mapping/NaturalIdLogging.java +++ b/hibernate-core/src/main/java/org/hibernate/engine/internal/NaturalIdLogging.java @@ -2,7 +2,7 @@ * SPDX-License-Identifier: Apache-2.0 * Copyright Red Hat Inc. and Hibernate Authors */ -package org.hibernate.metamodel.mapping; +package org.hibernate.engine.internal; import org.hibernate.Internal; import org.hibernate.internal.log.SubSystemLogging; @@ -25,7 +25,7 @@ */ @SubSystemLogging( name = NaturalIdLogging.LOGGER_NAME, - description = "Logging related to handling of natural-id mappings" + description = "Logging related to handling of natural id mappings" ) @MessageLogger(projectCode = "HHH") @ValidIdRange(min = 90001, max = 90100) diff --git a/hibernate-core/src/main/java/org/hibernate/engine/internal/NaturalIdResolutionsImpl.java b/hibernate-core/src/main/java/org/hibernate/engine/internal/NaturalIdResolutionsImpl.java index b6ac0cfbd6b9..f9227a3ae09d 100644 --- a/hibernate-core/src/main/java/org/hibernate/engine/internal/NaturalIdResolutionsImpl.java +++ b/hibernate-core/src/main/java/org/hibernate/engine/internal/NaturalIdResolutionsImpl.java @@ -35,7 +35,7 @@ import static java.util.Collections.emptyList; import static java.util.Collections.unmodifiableCollection; import static org.hibernate.engine.internal.CacheHelper.fromSharedCache; -import static org.hibernate.metamodel.mapping.NaturalIdLogging.NATURAL_ID_MESSAGE_LOGGER; +import static org.hibernate.engine.internal.NaturalIdLogging.NATURAL_ID_MESSAGE_LOGGER; public class NaturalIdResolutionsImpl implements NaturalIdResolutions, Serializable { private static final Logger LOG = Logger.getLogger( NaturalIdResolutionsImpl.class ); From e3d89dda98922378aee551c6e8769913e5873606 Mon Sep 17 00:00:00 2001 From: Gavin King Date: Sun, 13 Jul 2025 12:43:43 +0200 Subject: [PATCH 12/32] improve logging for Services and Statistics --- .../internal/AggregatedServiceLoader.java | 13 ++-- .../BootstrapServiceRegistryImpl.java | 10 +-- .../hibernate/internal/CoreMessageLogger.java | 64 ++++++++++--------- .../internal/AbstractServiceRegistryImpl.java | 28 ++++---- .../stat/internal/StatisticsImpl.java | 8 +++ .../stat/internal/StatisticsInitiator.java | 2 +- 6 files changed, 67 insertions(+), 58 deletions(-) diff --git a/hibernate-core/src/main/java/org/hibernate/boot/registry/classloading/internal/AggregatedServiceLoader.java b/hibernate-core/src/main/java/org/hibernate/boot/registry/classloading/internal/AggregatedServiceLoader.java index 7255076c2b21..32a55a717613 100644 --- a/hibernate-core/src/main/java/org/hibernate/boot/registry/classloading/internal/AggregatedServiceLoader.java +++ b/hibernate-core/src/main/java/org/hibernate/boot/registry/classloading/internal/AggregatedServiceLoader.java @@ -116,7 +116,7 @@ private Collection loadAll() { Set result = new LinkedHashSet<>(); // Always try the aggregated class loader first - Iterator> providerIterator = aggregatedClassLoaderServiceLoader.stream().iterator(); + var providerIterator = aggregatedClassLoaderServiceLoader.stream().iterator(); while ( providerIterator.hasNext() ) { ServiceLoader.Provider provider = providerIterator.next(); collectServiceIfNotDuplicate( result, alreadyEncountered, provider ); @@ -130,15 +130,14 @@ private Collection loadAll() { providerIterator = delegate.stream().iterator(); /* * Note that advancing the stream itself can lead to (arguably) "legitimate" errors, - * where we fail to load the service, - * but only because individual classloader has its own definition of the service contract class, - * which is different from ours. + * where we fail to load the service, but only because each individual classloader + * has its own definition of the service contract class, which is different from ours. * In that case (still arguably), the error should be ignored. - * That's why we wrap the call to hasNext in a method that catches an logs errors. + * That's why we wrap the call to hasNext in a method that catches and logs errors. * See https://hibernate.atlassian.net/browse/HHH-13551. */ while ( hasNextIgnoringServiceConfigurationError( providerIterator ) ) { - ServiceLoader.Provider provider = providerIterator.next(); + final ServiceLoader.Provider provider = providerIterator.next(); collectServiceIfNotDuplicate( result, alreadyEncountered, provider ); } } @@ -152,7 +151,7 @@ private boolean hasNextIgnoringServiceConfigurationError(Iterator iterator) { return iterator.hasNext(); } catch (ServiceConfigurationError e) { - log.ignoringServiceConfigurationError( serviceContract, e ); + log.ignoringServiceConfigurationError( serviceContract.getName(), e ); } } } diff --git a/hibernate-core/src/main/java/org/hibernate/boot/registry/internal/BootstrapServiceRegistryImpl.java b/hibernate-core/src/main/java/org/hibernate/boot/registry/internal/BootstrapServiceRegistryImpl.java index f470982bb3a4..29243db73073 100644 --- a/hibernate-core/src/main/java/org/hibernate/boot/registry/internal/BootstrapServiceRegistryImpl.java +++ b/hibernate-core/src/main/java/org/hibernate/boot/registry/internal/BootstrapServiceRegistryImpl.java @@ -240,22 +240,22 @@ public boolean isActive() { @Override public R initiateService(ServiceInitiator serviceInitiator) { - throw new ServiceException( "Boot-strap registry should only contain provided services" ); + throw new ServiceException( "Bootstrap registry should only contain provided services" ); } @Override public void configureService(ServiceBinding binding) { - throw new ServiceException( "Boot-strap registry should only contain provided services" ); + throw new ServiceException( "Bootstrap registry should only contain provided services" ); } @Override public void injectDependencies(ServiceBinding binding) { - throw new ServiceException( "Boot-strap registry should only contain provided services" ); + throw new ServiceException( "Bootstrap registry should only contain provided services" ); } @Override public void startService(ServiceBinding binding) { - throw new ServiceException( "Boot-strap registry should only contain provided services" ); + throw new ServiceException( "Bootstrap registry should only contain provided services" ); } @Override @@ -266,7 +266,7 @@ public synchronized void stopService(ServiceBinding bindi stoppable.stop(); } catch ( Exception e ) { - LOG.unableToStopService( service.getClass(), e ); + LOG.unableToStopService( binding.getServiceRole().getName(), e ); } } } diff --git a/hibernate-core/src/main/java/org/hibernate/internal/CoreMessageLogger.java b/hibernate-core/src/main/java/org/hibernate/internal/CoreMessageLogger.java index df039f0a7770..7b3d03c9ae5c 100644 --- a/hibernate-core/src/main/java/org/hibernate/internal/CoreMessageLogger.java +++ b/hibernate-core/src/main/java/org/hibernate/internal/CoreMessageLogger.java @@ -20,7 +20,6 @@ import org.hibernate.LockMode; import org.hibernate.cache.CacheException; import org.hibernate.id.IntegralDataTypeHolder; -import org.hibernate.service.Service; import org.hibernate.type.SerializationException; import org.jboss.logging.BasicLogger; @@ -33,7 +32,6 @@ import jakarta.transaction.Synchronization; import org.checkerframework.checker.nullness.qual.Nullable; -import static org.hibernate.cfg.JdbcSettings.CONNECTION_PROVIDER_DISABLES_AUTOCOMMIT; import static org.hibernate.cfg.ValidationSettings.JAKARTA_VALIDATION_MODE; import static org.jboss.logging.Logger.Level.DEBUG; import static org.jboss.logging.Logger.Level.ERROR; @@ -118,7 +116,7 @@ public interface CoreMessageLogger extends BasicLogger { void duplicateGeneratorName(String name); @LogMessage(level = INFO) - @Message(value = "entity-listener duplication, first event definition will be used: %s", id = 73) + @Message(value = "entity listener duplication, first event definition will be used: %s", id = 73) void duplicateListener(String className); @LogMessage(level = WARN) @@ -462,10 +460,6 @@ void missingArguments( @Message(value = "Error running schema update", id = 366) void unableToRunSchemaUpdate(@Cause Exception e); - @LogMessage(level = INFO) - @Message(value = "Error stopping service [%s]", id = 369) - void unableToStopService(Class class1, @Cause Exception e); - @LogMessage(level = ERROR) @Message(value = "Could not updateQuery hi value in: %s", id = 376) void unableToUpdateQueryHiValue(String tableName, @Cause SQLException e); @@ -563,13 +557,6 @@ void cannotResolveNonNullableTransientDependencies( ) void nonCompliantMapConversion(String collectionRole); - @LogMessage(level = WARN) - @Message( - id = 450, - value = "Encountered request for Service by non-primary service role [%s -> %s]; please update usage" - ) - void alternateServiceRole(String requestedRole, String targetRole); - @LogMessage(level = WARN) @Message( id = 451, @@ -671,10 +658,6 @@ void cannotResolveNonNullableTransientDependencies( @Message(value = "Multiple configuration properties defined to create schema. Choose at most one among 'jakarta.persistence.create-database-schemas' or 'hibernate.hbm2ddl.create_namespaces'.", id = 504) void multipleSchemaCreationSettingsDefined(); - @LogMessage(level = WARN) - @Message(value = "Ignoring ServiceConfigurationError caught while trying to instantiate service '%s'.", id = 505) - void ignoringServiceConfigurationError(Class serviceContract, @Cause ServiceConfigurationError error); - @LogMessage(level = WARN) @Message(value = "Detaching an uninitialized collection with enabled filters from a session: %s", id = 506) void enabledFiltersWhenDetachFromSession(String collectionInfoString); @@ -752,19 +735,6 @@ void unableToLocateStaticMetamodelField( ) void invalidJSONColumnType(String actual, String expected); - @LogMessage(level = DEBUG) - @Message( - id = 455, - value = - "'" + CONNECTION_PROVIDER_DISABLES_AUTOCOMMIT + "' " + - """ - was enabled. This setting should only be enabled when JDBC Connections obtained by Hibernate \ - from the ConnectionProvider have auto-commit disabled. Enabling this setting when connections \ - have auto-commit enabled leads to execution of SQL operations outside of any JDBC transaction.\ - """ - ) - void connectionProviderDisablesAutoCommitEnabled(); - @LogMessage(level = TRACE) @Message(value = "Closing logical connection", id = 456) void closingLogicalConnection(); @@ -773,6 +743,38 @@ void unableToLocateStaticMetamodelField( @Message(value = "Logical connection closed", id = 457) void logicalConnectionClosed(); + @LogMessage(level = TRACE) + @Message(value = "Statistics initialized", id = 460) + void statisticsInitialized(); + + @LogMessage(level = TRACE) + @Message(value = "Statistics collection enabled", id = 461) + void statisticsEnabled(); + + @LogMessage(level = TRACE) + @Message(value = "Statistics collection disabled", id = 462) + void statisticsDisabled(); + + @LogMessage(level = TRACE) + @Message(value = "Statistics reset", id = 463) + void statisticsReset(); + + @LogMessage(level = TRACE) + @Message(value = "Initializing service: %s", id = 500) + void initializingService(String serviceRole); + + @LogMessage(level = INFO) + @Message(value = "Error stopping service: %s", id = 369) + void unableToStopService(String serviceRole, @Cause Exception e); + + @LogMessage(level = WARN) + @Message(value = "Ignoring ServiceConfigurationError caught while instantiating service: %s", id = 505) + void ignoringServiceConfigurationError(String serviceContract, @Cause ServiceConfigurationError error); + + @LogMessage(level = WARN) + @Message(value = "Encountered request for service by non-primary service role [%s -> %s]", id = 450) + void alternateServiceRole(String requestedRole, String targetRole); + @LogMessage(level = DEBUG) @Message( id = 401, diff --git a/hibernate-core/src/main/java/org/hibernate/service/internal/AbstractServiceRegistryImpl.java b/hibernate-core/src/main/java/org/hibernate/service/internal/AbstractServiceRegistryImpl.java index a6d0451edb9b..f02de3b73114 100644 --- a/hibernate-core/src/main/java/org/hibernate/service/internal/AbstractServiceRegistryImpl.java +++ b/hibernate-core/src/main/java/org/hibernate/service/internal/AbstractServiceRegistryImpl.java @@ -183,9 +183,9 @@ private void registerAlternate(Class alternate, Class target) { @Override public @Nullable R getService(Class serviceRole) { - //Fast-path for ClassLoaderService as it's extremely hot during bootstrap - //(and after bootstrap service loading performance is less interesting as it's - //ideally being cached by long term consumers) + // Fast-path for ClassLoaderService as it's extremely hot during bootstrap + // (and after bootstrap service loading performance is less interesting as it's + // ideally being cached by long-term consumers) if ( ClassLoaderService.class == serviceRole ) { if ( parent != null ) { return parent.getService( serviceRole ); @@ -230,22 +230,22 @@ protected void registerService(ServiceBinding serviceBind private @Nullable R initializeService(ServiceBinding serviceBinding) { if ( log.isTraceEnabled() ) { - log.tracev( "Initializing service [role={0}]", serviceBinding.getServiceRole().getName() ); + log.initializingService( serviceBinding.getServiceRole().getName() ); } - // PHASE 1 : create service + // PHASE 1: create service R service = createService( serviceBinding ); if ( service == null ) { return null; } - // PHASE 2 : inject service (***potentially recursive***) + // PHASE 2: inject service (***potentially recursive***) serviceBinding.getLifecycleOwner().injectDependencies( serviceBinding ); - // PHASE 3 : configure service + // PHASE 3: configure service serviceBinding.getLifecycleOwner().configureService( serviceBinding ); - // PHASE 4 : Start service + // PHASE 4: Start service serviceBinding.getLifecycleOwner().startService( serviceBinding ); return service; @@ -260,8 +260,8 @@ protected void registerService(ServiceBinding serviceBind try { R service = serviceBinding.getLifecycleOwner().initiateService( serviceInitiator ); - // IMPL NOTE : the register call here is important to avoid potential stack overflow issues - // from recursive calls through #configureService + // IMPL NOTE: the register call here is important to avoid potential stack overflow issues + // from recursive calls through #configureService if ( service != null ) { registerService( serviceBinding, service ); } @@ -297,7 +297,7 @@ private void applyInjections(R service) { } } catch (NullPointerException e) { - log.error( "NPE injecting service deps : " + service.getClass().getName() ); + log.error( "NPE injecting service dependencies: " + service.getClass().getName() ); } } @@ -381,7 +381,7 @@ public synchronized void stopService(ServiceBinding bindi stoppable.stop(); } catch ( Exception e ) { - log.unableToStopService( service.getClass(), e ); + log.unableToStopService( binding.getServiceRole().getName(), e ); } } } @@ -393,7 +393,7 @@ public synchronized void registerChild(ServiceRegistryImplementor child) { } if ( !childRegistries.add( child ) ) { log.warnf( - "Child ServiceRegistry [%s] was already registered; this will end badly later...", + "Child ServiceRegistry [%s] was already registered; this will end badly later", child ); } @@ -411,7 +411,7 @@ public synchronized void deRegisterChild(ServiceRegistryImplementor child) { destroy(); } else { - log.trace( "Skipping destroying ServiceRegistry after deregistration of every child ServiceRegistru" ); + log.trace( "Skipping destroying ServiceRegistry after deregistration of every child ServiceRegistry" ); } } } diff --git a/hibernate-core/src/main/java/org/hibernate/stat/internal/StatisticsImpl.java b/hibernate-core/src/main/java/org/hibernate/stat/internal/StatisticsImpl.java index 6e86c06df019..4c8d773bd850 100644 --- a/hibernate-core/src/main/java/org/hibernate/stat/internal/StatisticsImpl.java +++ b/hibernate-core/src/main/java/org/hibernate/stat/internal/StatisticsImpl.java @@ -211,6 +211,8 @@ public void clear() { queryPlanCacheMissCount.reset(); resetStart(); + + log.statisticsReset(); } private void resetStart(@UnknownInitialization StatisticsImpl this) { @@ -235,6 +237,12 @@ public boolean isStatisticsEnabled() { @Override public void setStatisticsEnabled(boolean enabled) { isStatisticsEnabled = enabled; + if ( enabled ) { + log.statisticsEnabled(); + } + else { + log.statisticsDisabled(); + } } diff --git a/hibernate-core/src/main/java/org/hibernate/stat/internal/StatisticsInitiator.java b/hibernate-core/src/main/java/org/hibernate/stat/internal/StatisticsInitiator.java index 10b9a8caf04b..3ad678d60c8d 100644 --- a/hibernate-core/src/main/java/org/hibernate/stat/internal/StatisticsInitiator.java +++ b/hibernate-core/src/main/java/org/hibernate/stat/internal/StatisticsInitiator.java @@ -43,8 +43,8 @@ public StatisticsImplementor initiateService(SessionFactoryServiceInitiatorConte final StatisticsFactory statisticsFactory = statisticsFactory( configValue, context.getServiceRegistry() ); final StatisticsImplementor statistics = statisticsFactory.buildStatistics( context.getSessionFactory() ); final boolean enabled = context.getSessionFactoryOptions().isStatisticsEnabled(); + LOG.statisticsInitialized(); statistics.setStatisticsEnabled( enabled ); - LOG.tracef( "Statistics initialized [enabled=%s]", enabled ); return statistics; } From 60a413c9cb45d9da0bac88101e5bb92159567633 Mon Sep 17 00:00:00 2001 From: Gavin King Date: Sun, 13 Jul 2025 12:44:12 +0200 Subject: [PATCH 13/32] trivial changes to logging in JndiServiceImpl --- .../engine/jndi/internal/JndiServiceImpl.java | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/hibernate-core/src/main/java/org/hibernate/engine/jndi/internal/JndiServiceImpl.java b/hibernate-core/src/main/java/org/hibernate/engine/jndi/internal/JndiServiceImpl.java index 51dabfcd4de0..cf2bf62d8e74 100644 --- a/hibernate-core/src/main/java/org/hibernate/engine/jndi/internal/JndiServiceImpl.java +++ b/hibernate-core/src/main/java/org/hibernate/engine/jndi/internal/JndiServiceImpl.java @@ -167,7 +167,7 @@ public void bind(String jndiName, Object value) { private void bind(Name name, Object value, Context context) { try { - LOG.tracef( "Binding : %s", name ); + LOG.tracef( "Binding: %s", name ); context.rebind( name, value ); } catch ( Exception initialException ) { @@ -185,7 +185,7 @@ private void bind(Name name, Object value, Context context) { Context intermediateContext = null; try { - LOG.tracev( "Intermediate lookup: {0}", intermediateContextName ); + LOG.tracef( "Intermediate lookup: %s", intermediateContextName ); intermediateContext = (Context) intermediateContextBase.lookup( intermediateContextName ); } catch ( NameNotFoundException handledBelow ) { @@ -196,10 +196,10 @@ private void bind(Name name, Object value, Context context) { } if ( intermediateContext != null ) { - LOG.tracev( "Found intermediate context: {0}", intermediateContextName ); + LOG.tracef( "Found intermediate context: %s", intermediateContextName ); } else { - LOG.tracev( "Creating subcontext: {0}", intermediateContextName ); + LOG.tracef( "Creating subcontext: %s", intermediateContextName ); try { intermediateContext = intermediateContextBase.createSubcontext( intermediateContextName ); } @@ -210,7 +210,7 @@ private void bind(Name name, Object value, Context context) { intermediateContextBase = intermediateContext; name = name.getSuffix( 1 ); } - LOG.tracev( "Binding: {0}", name ); + LOG.tracef( "Binding: %s", name ); try { intermediateContextBase.rebind( name, value ); } From 142b9c6ec6f3b2ad518acf5ed8af17a54214877d Mon Sep 17 00:00:00 2001 From: Gavin King Date: Sun, 13 Jul 2025 12:46:59 +0200 Subject: [PATCH 14/32] move logging to JdbcEnvironmentInitiator to JdbcLogging --- .../hibernate/engine/jdbc/JdbcLogging.java | 21 +++++++++++++++++++ .../internal/JdbcEnvironmentInitiator.java | 21 +++++++------------ 2 files changed, 28 insertions(+), 14 deletions(-) diff --git a/hibernate-core/src/main/java/org/hibernate/engine/jdbc/JdbcLogging.java b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/JdbcLogging.java index 86d31d5740b4..c4f3a0fac767 100644 --- a/hibernate-core/src/main/java/org/hibernate/engine/jdbc/JdbcLogging.java +++ b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/JdbcLogging.java @@ -117,4 +117,25 @@ public interface JdbcLogging extends BasicLogger { """ ) void connectionProviderDisablesAutoCommitEnabled(); + + @LogMessage(level = DEBUG) + @Message(value = """ + Database: + name: %s + version: %s + major: %s + minor: %s""", + id = 100017) + void logDatabaseInfo(String name, String version, int major, int minor); + + @LogMessage(level = DEBUG) + @Message(value = """ + Driver: + name: %s + version: %s + major: %s + minor: %s + JDBC version: %s.%s""", + id = 100018) + void logDriverInfo(String name, String version, int major, int minor, int jdbcMajor, int jdbcMinor); } diff --git a/hibernate-core/src/main/java/org/hibernate/engine/jdbc/env/internal/JdbcEnvironmentInitiator.java b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/env/internal/JdbcEnvironmentInitiator.java index 7b7d0eb78e1a..eed397006a07 100644 --- a/hibernate-core/src/main/java/org/hibernate/engine/jdbc/env/internal/JdbcEnvironmentInitiator.java +++ b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/env/internal/JdbcEnvironmentInitiator.java @@ -49,6 +49,8 @@ import org.jboss.logging.Logger; +import static org.hibernate.engine.jdbc.JdbcLogging.JDBC_MESSAGE_LOGGER; + import static java.lang.Integer.parseInt; import static org.hibernate.cfg.AvailableSettings.CONNECTION_HANDLING; import static org.hibernate.cfg.AvailableSettings.DIALECT_DB_MAJOR_VERSION; @@ -430,29 +432,20 @@ private int databaseMicroVersion(DatabaseMetaData metadata) throws SQLException private static void logDatabaseAndDriver(DatabaseMetaData dbmd) throws SQLException { if ( log.isDebugEnabled() ) { - log.debugf( - "Database ->\n" - + " name: %s\n" - + " version: %s\n" - + " major: %s\n" - + " minor: %s", + JDBC_MESSAGE_LOGGER.logDatabaseInfo( dbmd.getDatabaseProductName(), dbmd.getDatabaseProductVersion(), dbmd.getDatabaseMajorVersion(), dbmd.getDatabaseMinorVersion() ); - log.debugf( - "Driver ->\n" - + " name: %s\n" - + " version: %s\n" - + " major: %s\n" - + " minor: %s", + JDBC_MESSAGE_LOGGER.logDriverInfo( dbmd.getDriverName(), dbmd.getDriverVersion(), dbmd.getDriverMajorVersion(), - dbmd.getDriverMinorVersion() + dbmd.getDriverMinorVersion(), + dbmd.getJDBCMajorVersion(), + dbmd.getJDBCMinorVersion() ); - log.debugf( "JDBC version: %s.%s", dbmd.getJDBCMajorVersion(), dbmd.getJDBCMinorVersion() ); } } From 13215a5455dc1434528aab0f046f5525102752b0 Mon Sep 17 00:00:00 2001 From: Gavin King Date: Sun, 13 Jul 2025 12:47:55 +0200 Subject: [PATCH 15/32] fix verbosity of logging in BootstrapContextImpl and ClassLoaderAccessImpl --- .../boot/internal/BootstrapContextImpl.java | 29 ++++++++++++++----- .../boot/internal/ClassLoaderAccessImpl.java | 13 ++++----- 2 files changed, 28 insertions(+), 14 deletions(-) diff --git a/hibernate-core/src/main/java/org/hibernate/boot/internal/BootstrapContextImpl.java b/hibernate-core/src/main/java/org/hibernate/boot/internal/BootstrapContextImpl.java index a1208d2497cf..ac3197496680 100644 --- a/hibernate-core/src/main/java/org/hibernate/boot/internal/BootstrapContextImpl.java +++ b/hibernate-core/src/main/java/org/hibernate/boot/internal/BootstrapContextImpl.java @@ -307,28 +307,43 @@ public void addAttributeConverterDescriptor(ConverterDescriptor descriptor) } } - void injectJpaTempClassLoader(ClassLoader jpaTempClassLoader) { - log.tracef( "Injecting JPA temp ClassLoader [%s] into BootstrapContext; was [%s]", jpaTempClassLoader, this.getJpaTempClassLoader() ); - this.classLoaderAccess.injectTempClassLoader( jpaTempClassLoader ); + void injectJpaTempClassLoader(ClassLoader classLoader) { + if ( log.isTraceEnabled() && classLoader != getJpaTempClassLoader() ) { + log.tracef( "Injecting JPA temp ClassLoader [%s] into BootstrapContext; was [%s]", + classLoader, getJpaTempClassLoader() ); + } + this.classLoaderAccess.injectTempClassLoader( classLoader ); } void injectScanOptions(ScanOptions scanOptions) { - log.tracef( "Injecting ScanOptions [%s] into BootstrapContext; was [%s]", scanOptions, this.scanOptions ); + if ( log.isTraceEnabled() && scanOptions != this.scanOptions ) { + log.tracef( "Injecting ScanOptions [%s] into BootstrapContext; was [%s]", + scanOptions, this.scanOptions ); + } this.scanOptions = scanOptions; } void injectScanEnvironment(ScanEnvironment scanEnvironment) { - log.tracef( "Injecting ScanEnvironment [%s] into BootstrapContext; was [%s]", scanEnvironment, this.scanEnvironment ); + if ( log.isTraceEnabled() && scanEnvironment != this.scanEnvironment ) { + log.tracef( "Injecting ScanEnvironment [%s] into BootstrapContext; was [%s]", + scanEnvironment, this.scanEnvironment ); + } this.scanEnvironment = scanEnvironment; } void injectScanner(Scanner scanner) { - log.tracef( "Injecting Scanner [%s] into BootstrapContext; was [%s]", scanner, this.scannerSetting ); + if ( log.isTraceEnabled() && scanner != this.scannerSetting ) { + log.tracef( "Injecting Scanner [%s] into BootstrapContext; was [%s]", + scanner, scannerSetting ); + } this.scannerSetting = scanner; } void injectArchiveDescriptorFactory(ArchiveDescriptorFactory factory) { - log.tracef( "Injecting ArchiveDescriptorFactory [%s] into BootstrapContext; was [%s]", factory, this.archiveDescriptorFactory ); + if ( log.isTraceEnabled() && factory != archiveDescriptorFactory ) { + log.tracef( "Injecting ArchiveDescriptorFactory [%s] into BootstrapContext; was [%s]", + factory, archiveDescriptorFactory ); + } this.archiveDescriptorFactory = factory; } diff --git a/hibernate-core/src/main/java/org/hibernate/boot/internal/ClassLoaderAccessImpl.java b/hibernate-core/src/main/java/org/hibernate/boot/internal/ClassLoaderAccessImpl.java index d10d8ed56dcc..5716a0302717 100644 --- a/hibernate-core/src/main/java/org/hibernate/boot/internal/ClassLoaderAccessImpl.java +++ b/hibernate-core/src/main/java/org/hibernate/boot/internal/ClassLoaderAccessImpl.java @@ -54,20 +54,19 @@ public Class classForName(String name) { return classLoaderService.classForName( name ); } else { - log.tracef( "Not known whether passed class name [%s] is safe", name ); + // Could not determine that the given class is safe to load with live ClassLoader if ( jpaTempClassLoader == null ) { log.tracef( - "No temp ClassLoader provided; using live ClassLoader " + - "for loading potentially unsafe class: %s", + "No temp ClassLoader provided; using live ClassLoader to load potentially unsafe class: %s", name ); return classLoaderService.classForName( name ); } else { - log.tracef( - "Temp ClassLoader was provided, so we will use that: %s", - name - ); +// log.tracef( +// "Temp ClassLoader was provided, so we will use that: %s", +// name +// ); try { return jpaTempClassLoader.loadClass( name ); } From 6c7d383c340f1bdc7f02f73d2309bdea24b484a7 Mon Sep 17 00:00:00 2001 From: Gavin King Date: Sun, 13 Jul 2025 12:48:25 +0200 Subject: [PATCH 16/32] improve log message in StrategySelectorImpl --- .../internal/StrategySelectorImpl.java | 34 ++++++++----------- 1 file changed, 14 insertions(+), 20 deletions(-) diff --git a/hibernate-core/src/main/java/org/hibernate/boot/registry/selector/internal/StrategySelectorImpl.java b/hibernate-core/src/main/java/org/hibernate/boot/registry/selector/internal/StrategySelectorImpl.java index fa39cda3ed40..c4e35764e14a 100644 --- a/hibernate-core/src/main/java/org/hibernate/boot/registry/selector/internal/StrategySelectorImpl.java +++ b/hibernate-core/src/main/java/org/hibernate/boot/registry/selector/internal/StrategySelectorImpl.java @@ -201,28 +201,22 @@ private void contributeImplementation(Class strategy, Class for ( String name : names ) { final Class old = namedStrategyImplementorMap.put( name, implementation ); - if ( old == null ) { - if ( log.isTraceEnabled() ) { - log.trace( - String.format( - "Registering named strategy selector [%s] : [%s] -> [%s]", - strategy.getName(), - name, - implementation.getName() - ) + if ( log.isTraceEnabled() ) { + if ( old == null ) { + log.tracef( + "Strategy selector for %s: '%s' -> %s", + strategy.getSimpleName(), + name, + implementation.getName() ); } - } - else { - if ( log.isTraceEnabled() ) { - log.trace( - String.format( - "Registering named strategy selector [%s] : [%s] -> [%s] (replacing [%s])", - strategy.getName(), - name, - implementation.getName(), - old.getName() - ) + else { + log.tracef( + "Strategy selector for %s: '%s' -> %s (replacing %s)", + strategy.getSimpleName(), + name, + implementation.getName(), + old.getName() ); } } From 639a7b9b145f1861e74dc3475135c607dbd3733b Mon Sep 17 00:00:00 2001 From: Gavin King Date: Sun, 13 Jul 2025 12:49:18 +0200 Subject: [PATCH 17/32] slightly improve format of log message in AttributeFactory --- .../org/hibernate/metamodel/internal/AttributeFactory.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/hibernate-core/src/main/java/org/hibernate/metamodel/internal/AttributeFactory.java b/hibernate-core/src/main/java/org/hibernate/metamodel/internal/AttributeFactory.java index bedbebb48481..1a52b6486f26 100644 --- a/hibernate-core/src/main/java/org/hibernate/metamodel/internal/AttributeFactory.java +++ b/hibernate-core/src/main/java/org/hibernate/metamodel/internal/AttributeFactory.java @@ -443,11 +443,11 @@ private static AttributeMetadata determineAttributeMetadata( log.tracef( "Starting attribute metadata determination [%s]", propertyName ); final Member member = memberResolver.resolveMember( attributeContext, context ); - log.tracef( " Determined member [%s]", member ); + log.tracef( "\tMember: %s", member ); final Value value = propertyMapping.getValue(); final org.hibernate.type.Type type = value.getType(); - log.tracef( " Determined type [name=%s, class=%s]", type.getName(), type.getClass().getName() ); + log.tracef( "\tType: %s [%s]", type.getName(), type.getClass().getSimpleName() ); if ( type instanceof AnyType ) { return new SingularAttributeMetadataImpl<>( From 4133366a54794eb332b2b851f8eb07b588addeb1 Mon Sep 17 00:00:00 2001 From: Gavin King Date: Sun, 13 Jul 2025 12:50:02 +0200 Subject: [PATCH 18/32] more consistent format for logging in boot.model package --- .../boot/model/internal/CollectionBinder.java | 10 +++++----- .../boot/model/internal/EmbeddableBinder.java | 2 +- .../boot/model/internal/EntityBinder.java | 2 +- .../boot/model/internal/QueryBinder.java | 15 ++++++++------- .../model/source/internal/hbm/ModelBinder.java | 4 ++-- 5 files changed, 17 insertions(+), 16 deletions(-) diff --git a/hibernate-core/src/main/java/org/hibernate/boot/model/internal/CollectionBinder.java b/hibernate-core/src/main/java/org/hibernate/boot/model/internal/CollectionBinder.java index e139ebf02f45..fdc4aecd0f4d 100644 --- a/hibernate-core/src/main/java/org/hibernate/boot/model/internal/CollectionBinder.java +++ b/hibernate-core/src/main/java/org/hibernate/boot/model/internal/CollectionBinder.java @@ -2804,7 +2804,7 @@ private void setLocalGenerators(Map local private void logOneToManySecondPass() { if ( LOG.isTraceEnabled() ) { - LOG.trace( "Binding @OneToMany through foreign key: " + safeCollectionRole() ); + LOG.trace( "Binding one-to-many association through foreign key: " + safeCollectionRole() ); } } @@ -2814,16 +2814,16 @@ private void logManyToManySecondPass( boolean isManyToAny) { if ( LOG.isTraceEnabled() ) { if ( isCollectionOfEntities && isOneToMany ) { - LOG.trace( "Binding @OneToMany through association table: " + safeCollectionRole() ); + LOG.trace( "Binding one-to-many association through association table: " + safeCollectionRole() ); } else if ( isCollectionOfEntities ) { - LOG.trace( "Binding @ManyToMany through association table: " + safeCollectionRole() ); + LOG.trace( "Binding many-to-many association through association table: " + safeCollectionRole() ); } else if ( isManyToAny ) { - LOG.trace( "Binding @ManyToAny: " + safeCollectionRole() ); + LOG.trace( "Binding many-to-any: " + safeCollectionRole() ); } else { - LOG.trace( "Binding @ElementCollection to collection table: " + safeCollectionRole() ); + LOG.trace( "Binding element collection to collection table: " + safeCollectionRole() ); } } } diff --git a/hibernate-core/src/main/java/org/hibernate/boot/model/internal/EmbeddableBinder.java b/hibernate-core/src/main/java/org/hibernate/boot/model/internal/EmbeddableBinder.java index 023cc1484d5b..d0b195452b2a 100644 --- a/hibernate-core/src/main/java/org/hibernate/boot/model/internal/EmbeddableBinder.java +++ b/hibernate-core/src/main/java/org/hibernate/boot/model/internal/EmbeddableBinder.java @@ -453,7 +453,7 @@ static Component fillEmbeddable( final String subpath = getPath( propertyHolder, inferredData ); if ( LOG.isTraceEnabled() ) { - LOG.trace( "Binding component with path: " + subpath ); + LOG.trace( "Binding embeddable with path: " + subpath ); } final PropertyHolder subholder = buildPropertyHolder( component, diff --git a/hibernate-core/src/main/java/org/hibernate/boot/model/internal/EntityBinder.java b/hibernate-core/src/main/java/org/hibernate/boot/model/internal/EntityBinder.java index 9b06f080a102..7f4855223789 100644 --- a/hibernate-core/src/main/java/org/hibernate/boot/model/internal/EntityBinder.java +++ b/hibernate-core/src/main/java/org/hibernate/boot/model/internal/EntityBinder.java @@ -180,7 +180,7 @@ public static void bindEntityClass( Map inheritanceStates, MetadataBuildingContext context) { if ( LOG.isTraceEnabled() ) { - LOG.trace( "Binding entity from annotated class: " + clazzToProcess.getName() ); + LOG.trace( "Binding entity with annotated class: " + clazzToProcess.getName() ); } final InFlightMetadataCollector collector = context.getMetadataCollector(); diff --git a/hibernate-core/src/main/java/org/hibernate/boot/model/internal/QueryBinder.java b/hibernate-core/src/main/java/org/hibernate/boot/model/internal/QueryBinder.java index 5bfbbd9dd9ad..95fbccca00ea 100644 --- a/hibernate-core/src/main/java/org/hibernate/boot/model/internal/QueryBinder.java +++ b/hibernate-core/src/main/java/org/hibernate/boot/model/internal/QueryBinder.java @@ -81,7 +81,8 @@ public static void bindQuery( } if ( LOG.isTraceEnabled() ) { - LOG.tracef( "Binding named query: %s => %s", queryName, queryString ); + LOG.tracef( "Binding named query '%s' to [%s]", queryName, + queryString.replace( '\n', ' ' ) ); } final QueryHintDefinition hints = new QueryHintDefinition( queryName, namedQuery.hints() ); @@ -141,9 +142,9 @@ public static void bindNativeQuery( createNamedQueryDefinition( registrationName, queryString, resultClass, resultSetMappingName, hints, location ); if ( LOG.isTraceEnabled() ) { - LOG.tracef( "Binding named native query: %s => %s", + LOG.tracef( "Binding named native query '%s' to [%s]", queryDefinition.getRegistrationName(), - queryDefinition.getSqlQueryString() ); + queryDefinition.getSqlQueryString().replace( '\n', ' ' ) ); } if ( isDefault ) { @@ -234,9 +235,9 @@ public static void bindNativeQuery( final NamedNativeQueryDefinition queryDefinition = builder.build(); if ( LOG.isTraceEnabled() ) { LOG.tracef( - "Binding named native query: %s => %s", + "Binding named native query '%' to [%s]", queryDefinition.getRegistrationName(), - queryDefinition.getSqlQueryString() + queryDefinition.getSqlQueryString().replace( '\n', ' ' ) ); } context.getMetadataCollector().addNamedNativeQuery( queryDefinition ); @@ -390,9 +391,9 @@ public static void bindQuery( final NamedHqlQueryDefinitionImpl hqlQueryDefinition = builder.build(); if ( LOG.isTraceEnabled() ) { - LOG.tracef( "Binding named query: %s => %s", + LOG.tracef( "Binding named query '%s' to [%s]", hqlQueryDefinition.getRegistrationName(), - hqlQueryDefinition.getHqlString() ); + hqlQueryDefinition.getHqlString().replace( '\n', ' ' ) ); } context.getMetadataCollector().addNamedQuery( hqlQueryDefinition ); diff --git a/hibernate-core/src/main/java/org/hibernate/boot/model/source/internal/hbm/ModelBinder.java b/hibernate-core/src/main/java/org/hibernate/boot/model/source/internal/hbm/ModelBinder.java index 18f2137186ee..9afa44c11130 100644 --- a/hibernate-core/src/main/java/org/hibernate/boot/model/source/internal/hbm/ModelBinder.java +++ b/hibernate-core/src/main/java/org/hibernate/boot/model/source/internal/hbm/ModelBinder.java @@ -2454,7 +2454,7 @@ private void bindComponent( // todo : better define the conditions in this if/else if ( isDynamic ) { // dynamic is represented as a Map - log.tracef( "Binding dynamic-component [%s]", role ); + log.tracef( "Binding dynamic component [%s]", role ); componentBinding.setDynamic( true ); } else if ( isVirtual ) { @@ -2983,7 +2983,7 @@ public void doSecondPass(Map persistentClasses) throws collectionBinding.createAllKeys(); if ( log.isTraceEnabled() ) { - log.tracef( "Mapped collection : %s", getPluralAttributeSource().getAttributeRole().getFullPath() ); + log.tracef( "Mapped collection: %s", getPluralAttributeSource().getAttributeRole().getFullPath() ); log.tracef( " + table -> %s", getCollectionBinding().getTable().getName() ); log.tracef( " + key -> %s", columns( getCollectionBinding().getKey() ) ); if ( getCollectionBinding().isIndexed() ) { From a70ea5e162ddfc2a84e8819324013b91342cd6a8 Mon Sep 17 00:00:00 2001 From: Gavin King Date: Sun, 13 Jul 2025 13:00:00 +0200 Subject: [PATCH 19/32] remove another ugly log message from query compiler --- .../hibernate/query/hql/internal/DomainPathPart.java | 11 +++++------ 1 file changed, 5 insertions(+), 6 deletions(-) diff --git a/hibernate-core/src/main/java/org/hibernate/query/hql/internal/DomainPathPart.java b/hibernate-core/src/main/java/org/hibernate/query/hql/internal/DomainPathPart.java index 1de5e3dfa10d..3b28d7d95f18 100644 --- a/hibernate-core/src/main/java/org/hibernate/query/hql/internal/DomainPathPart.java +++ b/hibernate-core/src/main/java/org/hibernate/query/hql/internal/DomainPathPart.java @@ -4,7 +4,6 @@ */ package org.hibernate.query.hql.internal; -import org.hibernate.query.hql.HqlLogging; import org.hibernate.query.hql.spi.SemanticPathPart; import org.hibernate.query.hql.spi.SqmCreationState; import org.hibernate.query.sqm.tree.domain.SqmPath; @@ -32,11 +31,11 @@ public SemanticPathPart resolvePathPart( String name, boolean isTerminal, SqmCreationState creationState) { - HqlLogging.QUERY_LOGGER.tracef( - "Resolving DomainPathPart(%s) sub-part : %s", - currentPath, - name - ); +// HqlLogging.QUERY_LOGGER.tracef( +// "Resolving DomainPathPart(%s) sub-part : %s", +// currentPath, +// name +// ); currentPath = currentPath.resolvePathPart( name, isTerminal, creationState ); if ( isTerminal ) { return currentPath; From f3baef5a1e005af5fb8730d401b4cdabaf76b937 Mon Sep 17 00:00:00 2001 From: Gavin King Date: Sun, 13 Jul 2025 13:00:34 +0200 Subject: [PATCH 20/32] disable TRACE logging from type registries at least for now - it was just too verbose --- .../org/hibernate/type/BasicTypeRegistry.java | 70 +++++++++---------- .../descriptor/jdbc/spi/JdbcTypeRegistry.java | 32 ++++----- .../descriptor/sql/spi/DdlTypeRegistry.java | 5 +- 3 files changed, 51 insertions(+), 56 deletions(-) diff --git a/hibernate-core/src/main/java/org/hibernate/type/BasicTypeRegistry.java b/hibernate-core/src/main/java/org/hibernate/type/BasicTypeRegistry.java index 29a98212ff52..3ce06f230a0f 100644 --- a/hibernate-core/src/main/java/org/hibernate/type/BasicTypeRegistry.java +++ b/hibernate-core/src/main/java/org/hibernate/type/BasicTypeRegistry.java @@ -385,51 +385,49 @@ private Map, BasicType> registryForJdbcType(JdbcType jdbcType) { private void applyRegistrationKeys(BasicType type, String[] keys) { for ( String key : keys ) { - // be safe... - if ( key == null ) { - continue; + if ( key != null ) { + // Use String.intern here as there's a high probability of duplicates combined with long-term usage: + // just running our testsuite would generate 210,000 instances for the String "java.lang.Class" alone. + // Incidentally, this might also help with map lookup efficiency. + key = key.intern(); + + // Incredibly verbose logging disabled +// LOG.tracef( "Adding type registration %s -> %s", key, type ); + + final Type old = typesByName.put( key, type ); +// if ( old != null && old != type ) { +// LOG.tracef( +// "Type registration key [%s] overrode previous entry : `%s`", +// key, +// old +// ); +// } } - //Use String#intern here as there's high chances of duplicates combined with long term usage: - //just running our testsuite would generate 210,000 instances for the String "java.lang.Class" alone. - //Incidentally this might help with map lookup efficiency too. - key = key.intern(); - - LOG.tracef( "Adding type registration %s -> %s", key, type ); - - final Type old = typesByName.put( key, type ); - if ( old != null && old != type ) { - LOG.tracef( - "Type registration key [%s] overrode previous entry : `%s`", - key, - old - ); - } } } private void applyRegistrationKeys(BasicTypeReference type, String[] keys) { for ( String key : keys ) { - // be safe... - if ( key == null ) { - continue; + if ( key != null ) { + // Use String.intern here as there's a high probability of duplicates combined with long-term usage: + // just running our testsuite would generate 210,000 instances for the String "java.lang.Class" alone. + // Incidentally, this might also help with map lookup efficiency. + key = key.intern(); + + // Incredibly verbose logging disabled +// LOG.tracef( "Adding type registration %s -> %s", key, type ); + + final BasicTypeReference old = typeReferencesByName.put( key, type ); +// if ( old != null && old != type ) { +// LOG.tracef( +// "Type registration key [%s] overrode previous entry : `%s`", +// key, +// old +// ); +// } } - //Use String#intern here as there's high chances of duplicates combined with long term usage: - //just running our testsuite would generate 210,000 instances for the String "java.lang.Class" alone. - //Incidentally this might help with map lookup efficiency too. - key = key.intern(); - - LOG.tracef( "Adding type registration %s -> %s", key, type ); - - final BasicTypeReference old = typeReferencesByName.put( key, type ); - if ( old != null && old != type ) { - LOG.tracef( - "Type registration key [%s] overrode previous entry : `%s`", - key, - old - ); - } } } } diff --git a/hibernate-core/src/main/java/org/hibernate/type/descriptor/jdbc/spi/JdbcTypeRegistry.java b/hibernate-core/src/main/java/org/hibernate/type/descriptor/jdbc/spi/JdbcTypeRegistry.java index 8894708f7d79..c28f99e17067 100644 --- a/hibernate-core/src/main/java/org/hibernate/type/descriptor/jdbc/spi/JdbcTypeRegistry.java +++ b/hibernate-core/src/main/java/org/hibernate/type/descriptor/jdbc/spi/JdbcTypeRegistry.java @@ -24,8 +24,6 @@ import org.hibernate.type.descriptor.jdbc.internal.JdbcTypeBaseline; import org.hibernate.type.spi.TypeConfiguration; -import org.jboss.logging.Logger; - import org.checkerframework.checker.nullness.qual.Nullable; import static org.hibernate.type.descriptor.JdbcTypeNameMapper.isStandardTypeCode; @@ -40,7 +38,7 @@ * @since 5.3 */ public class JdbcTypeRegistry implements JdbcTypeBaseline.BaselineTarget, Serializable { - private static final Logger log = Logger.getLogger( JdbcTypeRegistry.class ); +// private static final Logger log = Logger.getLogger( JdbcTypeRegistry.class ); private final TypeConfiguration typeConfiguration; private final ConcurrentHashMap descriptorMap = new ConcurrentHashMap<>(); @@ -69,17 +67,17 @@ public TypeConfiguration getTypeConfiguration() { @Override public void addDescriptor(JdbcType jdbcType) { final JdbcType previous = descriptorMap.put( jdbcType.getDefaultSqlTypeCode(), jdbcType ); - if ( previous != null && previous != jdbcType ) { - log.tracef( "addDescriptor(%s) replaced previous registration(%s)", jdbcType, previous ); - } +// if ( previous != null && previous != jdbcType ) { +// log.tracef( "addDescriptor(%s) replaced previous registration(%s)", jdbcType, previous ); +// } } @Override public void addDescriptor(int typeCode, JdbcType jdbcType) { final JdbcType previous = descriptorMap.put( typeCode, jdbcType ); - if ( previous != null && previous != jdbcType ) { - log.tracef( "addDescriptor(%d, %s) replaced previous registration(%s)", typeCode, jdbcType, previous ); - } +// if ( previous != null && previous != jdbcType ) { +// log.tracef( "addDescriptor(%d, %s) replaced previous registration(%s)", typeCode, jdbcType, previous ); +// } } public void addDescriptorIfAbsent(JdbcType jdbcType) { @@ -100,10 +98,10 @@ public JdbcType getDescriptor(int jdbcTypeCode) { return descriptor; } else { - if ( isStandardTypeCode( jdbcTypeCode ) ) { - log.debugf( "A standard JDBC type code [%s] was not defined in SqlTypeDescriptorRegistry", - jdbcTypeCode ); - } +// if ( isStandardTypeCode( jdbcTypeCode ) ) { +// log.debugf( "A standard JDBC type code [%s] was not defined in SqlTypeDescriptorRegistry", +// jdbcTypeCode ); +// } // see if the typecode is part of a known type family... final JdbcType potentialAlternateDescriptor = getFamilyDescriptor( jdbcTypeCode ); @@ -130,10 +128,10 @@ private JdbcType getFamilyDescriptor(int jdbcTypeCode) { // todo (6.0) : add a SqlTypeDescriptor#canBeAssignedFrom method ? return potentialAlternateDescriptor; } - if ( isStandardTypeCode( potentialAlternateTypeCode ) ) { - log.debugf( "A standard JDBC type code [%s] was not defined in SqlTypeDescriptorRegistry", - potentialAlternateTypeCode ); - } +// if ( isStandardTypeCode( potentialAlternateTypeCode ) ) { +// log.debugf( "A standard JDBC type code [%s] was not defined in SqlTypeDescriptorRegistry", +// potentialAlternateTypeCode ); +// } } } } diff --git a/hibernate-core/src/main/java/org/hibernate/type/descriptor/sql/spi/DdlTypeRegistry.java b/hibernate-core/src/main/java/org/hibernate/type/descriptor/sql/spi/DdlTypeRegistry.java index 888811f6d693..30a06033008c 100644 --- a/hibernate-core/src/main/java/org/hibernate/type/descriptor/sql/spi/DdlTypeRegistry.java +++ b/hibernate-core/src/main/java/org/hibernate/type/descriptor/sql/spi/DdlTypeRegistry.java @@ -19,7 +19,6 @@ import org.hibernate.type.descriptor.sql.DdlType; import org.hibernate.type.spi.TypeConfiguration; -import org.jboss.logging.Logger; /** * A registry mapping {@link org.hibernate.type.SqlTypes JDBC type codes} @@ -30,7 +29,7 @@ * @since 6.0 */ public class DdlTypeRegistry implements Serializable { - private static final Logger log = Logger.getLogger( DdlTypeRegistry.class ); +// private static final Logger log = Logger.getLogger( DdlTypeRegistry.class ); private final Map ddlTypes = new HashMap<>(); private final Map sqlTypes = new TreeMap<>( String.CASE_INSENSITIVE_ORDER ); @@ -59,7 +58,7 @@ public void addDescriptor(int sqlTypeCode, DdlType ddlType) { for ( String rawTypeName : previous.getRawTypeNames() ) { sqlTypes.remove( rawTypeName ); } - log.tracef( "addDescriptor(%d, %s) replaced previous registration(%s)", sqlTypeCode, ddlType, previous ); +// log.tracef( "addDescriptor(%d, %s) replaced previous registration(%s)", sqlTypeCode, ddlType, previous ); } addSqlType( ddlType, sqlTypeCode ); } From a9f8e4b707e5375767aac6550cd28890ee013bd2 Mon Sep 17 00:00:00 2001 From: Gavin King Date: Sun, 13 Jul 2025 13:01:12 +0200 Subject: [PATCH 21/32] disable TRACE logging from SqmFunctionRegistry at least for now - it was just too ugly and verbose --- .../sqm/function/SqmFunctionRegistry.java | 34 +++++++++---------- 1 file changed, 17 insertions(+), 17 deletions(-) diff --git a/hibernate-core/src/main/java/org/hibernate/query/sqm/function/SqmFunctionRegistry.java b/hibernate-core/src/main/java/org/hibernate/query/sqm/function/SqmFunctionRegistry.java index 5620a0dbcaad..ae9dde835322 100644 --- a/hibernate-core/src/main/java/org/hibernate/query/sqm/function/SqmFunctionRegistry.java +++ b/hibernate-core/src/main/java/org/hibernate/query/sqm/function/SqmFunctionRegistry.java @@ -18,8 +18,6 @@ import org.hibernate.type.BasicType; import org.hibernate.type.spi.TypeConfiguration; -import org.jboss.logging.Logger; - import org.checkerframework.checker.nullness.qual.Nullable; import static java.lang.String.CASE_INSENSITIVE_ORDER; @@ -36,14 +34,14 @@ * @author Steve Ebersole */ public class SqmFunctionRegistry { - private static final Logger log = Logger.getLogger( SqmFunctionRegistry.class ); +// private static final Logger log = Logger.getLogger( SqmFunctionRegistry.class ); private final CaseInsensitiveDictionary functionMap = new CaseInsensitiveDictionary<>(); private final CaseInsensitiveDictionary setReturningFunctionMap = new CaseInsensitiveDictionary<>(); private final CaseInsensitiveDictionary alternateKeyMap = new CaseInsensitiveDictionary<>(); public SqmFunctionRegistry() { - log.trace( "SqmFunctionRegistry created" ); +// log.trace( "SqmFunctionRegistry created" ); } public Set getValidFunctionKeys() { @@ -121,12 +119,13 @@ public Stream> getSetReturn */ public SqmFunctionDescriptor register(String registrationKey, SqmFunctionDescriptor function) { final SqmFunctionDescriptor priorRegistration = functionMap.put( registrationKey, function ); - log.tracef( - "Registered SqmFunctionTemplate [%s] under %s; prior registration was %s", - function, - registrationKey, - priorRegistration - ); + // Incredibly verbose logging disabled +// log.tracef( +// "Registered SqmFunctionTemplate [%s] under %s; prior registration was %s", +// function, +// registrationKey, +// priorRegistration +// ); alternateKeyMap.remove( registrationKey ); return function; } @@ -136,12 +135,12 @@ public SqmFunctionDescriptor register(String registrationKey, SqmFunctionDescrip */ public SqmSetReturningFunctionDescriptor register(String registrationKey, SqmSetReturningFunctionDescriptor function) { final SqmSetReturningFunctionDescriptor priorRegistration = setReturningFunctionMap.put( registrationKey, function ); - log.tracef( - "Registered SqmSetReturningFunctionTemplate [%s] under %s; prior registration was %s", - function, - registrationKey, - priorRegistration - ); +// log.tracef( +// "Registered SqmSetReturningFunctionTemplate [%s] under %s; prior registration was %s", +// function, +// registrationKey, +// priorRegistration +// ); alternateKeyMap.remove( registrationKey ); return function; } @@ -385,7 +384,8 @@ public SqmFunctionDescriptor wrapInJdbcEscape(String name, SqmFunctionDescriptor public void registerAlternateKey(String alternateKey, String mappedKey) { assert functionMap.containsKey( mappedKey ); - log.tracef( "Registering alternate key : %s -> %s", alternateKey, mappedKey ); + // Incredibly verbose logging disabled +// log.tracef( "Registering alternate key : %s -> %s", alternateKey, mappedKey ); alternateKeyMap.put( alternateKey, mappedKey ); } From b78d8eff2e0358f0a166d68ba07cbea8cb208b07 Mon Sep 17 00:00:00 2001 From: Gavin King Date: Sun, 13 Jul 2025 23:09:37 +0200 Subject: [PATCH 22/32] Big clean up around natural id stuff motivated by work on logging cleanup --- .../engine/internal/NaturalIdLogging.java | 6 +- .../hibernate/internal/NaturalIdHelper.java | 88 ++--- .../ast/internal/AbstractNaturalIdLoader.java | 336 +++++++++--------- .../ast/internal/CompoundNaturalIdLoader.java | 75 ++-- .../loader/ast/internal/LoaderHelper.java | 17 +- .../ast/internal/SimpleNaturalIdLoader.java | 52 +-- .../internal/BaseNaturalIdLoadAccessImpl.java | 68 ++-- .../internal/NaturalIdLoadAccessImpl.java | 7 +- .../SimpleNaturalIdLoadAccessImpl.java | 20 +- .../internal/CompoundNaturalIdMapping.java | 2 +- .../entity/AbstractEntityPersister.java | 7 - 11 files changed, 293 insertions(+), 385 deletions(-) diff --git a/hibernate-core/src/main/java/org/hibernate/engine/internal/NaturalIdLogging.java b/hibernate-core/src/main/java/org/hibernate/engine/internal/NaturalIdLogging.java index 80cff5cc8246..f81de3c9fb49 100644 --- a/hibernate-core/src/main/java/org/hibernate/engine/internal/NaturalIdLogging.java +++ b/hibernate-core/src/main/java/org/hibernate/engine/internal/NaturalIdLogging.java @@ -52,10 +52,14 @@ public interface NaturalIdLogging extends BasicLogger { void removingLocallyCachedNaturalIdResolution(String entityName, Object naturalId, Object id); @LogMessage(level = TRACE) - @Message(value = "Resolved natural key [%s] -> primary key [%s] resolution in session cache for [%s]:", id = 90004) + @Message(value = "Resolved natural key [%s] -> primary key [%s] resolution in session cache for [%s]", id = 90004) void resolvedNaturalIdInSessionCache(Object naturalId, Object pk, String entityName); @LogMessage(level = TRACE) @Message(value = "Found natural key [%s] -> primary key [%s] xref in second-level cache for [%s]", id = 90005) void foundNaturalIdInSecondLevelCache(Object naturalId, Object pk, String entityName); + + @LogMessage(level = TRACE) + @Message(value = "Retrieving primary key of %s from database for natural id: %s", id = 90006) + void retrievingIdForNaturalId(String entityName, Object naturalId); } diff --git a/hibernate-core/src/main/java/org/hibernate/internal/NaturalIdHelper.java b/hibernate-core/src/main/java/org/hibernate/internal/NaturalIdHelper.java index fe7043c864a1..d91b86081145 100644 --- a/hibernate-core/src/main/java/org/hibernate/internal/NaturalIdHelper.java +++ b/hibernate-core/src/main/java/org/hibernate/internal/NaturalIdHelper.java @@ -10,17 +10,18 @@ import org.hibernate.engine.spi.SharedSessionContractImplementor; import org.hibernate.engine.spi.Status; import org.hibernate.id.IdentifierGenerationException; -import org.hibernate.loader.LoaderLogging; import org.hibernate.metamodel.mapping.EntityMappingType; -import org.hibernate.metamodel.mapping.NaturalIdMapping; import org.hibernate.persister.entity.EntityPersister; import java.util.Collection; +import static org.hibernate.engine.internal.NaturalIdLogging.NATURAL_ID_LOGGER; + /** * @author Gavin King */ public class NaturalIdHelper { + public static String[] getNaturalIdPropertyNames(EntityPersister persister) { final int[] naturalIdPropertyIndices = persister.getNaturalIdentifierProperties(); if ( naturalIdPropertyIndices == null ) { @@ -43,58 +44,41 @@ public static void performAnyNeededCrossReferenceSynchronizations( boolean synchronizationEnabled, EntityMappingType entityMappingType, SharedSessionContractImplementor session) { - - if ( !synchronizationEnabled ) { - // synchronization (this process) was disabled - return; - } - - final NaturalIdMapping naturalIdMapping = entityMappingType.getNaturalIdMapping(); - - if ( !naturalIdMapping.isMutable() ) { - // only mutable natural-ids need this processing - return; - } - - if ( ! session.isTransactionInProgress() ) { - // not in a transaction so skip synchronization - return; - } - - final EntityPersister entityPersister = entityMappingType.getEntityPersister(); - - final PersistenceContext persistenceContext = session.getPersistenceContextInternal(); - final Collection cachedPkResolutions = - persistenceContext.getNaturalIdResolutions() - .getCachedPkResolutions( entityPersister ); - final boolean loggerDebugEnabled = LoaderLogging.LOADER_LOGGER.isDebugEnabled(); - for ( Object pk : cachedPkResolutions ) { - final EntityKey entityKey = session.generateEntityKey( pk, entityPersister ); - final Object entity = persistenceContext.getEntity( entityKey ); - final EntityEntry entry = persistenceContext.getEntry( entity ); - - if ( entry == null ) { - if ( loggerDebugEnabled ) { - LoaderLogging.LOADER_LOGGER.debugf( - "Cached natural-id/pk resolution linked to null EntityEntry in persistence context: %s#%s", - entityMappingType.getEntityName(), - pk - ); + // first check if synchronization (this process) was disabled + if ( synchronizationEnabled + // only mutable natural-ids need this processing + && entityMappingType.getNaturalIdMapping().isMutable() + // skip synchronization when not in a transaction + && session.isTransactionInProgress() ) { + final EntityPersister entityPersister = entityMappingType.getEntityPersister(); + final PersistenceContext persistenceContext = session.getPersistenceContextInternal(); + final Collection cachedResolutions = + persistenceContext.getNaturalIdResolutions() + .getCachedPkResolutions( entityPersister ); + final boolean loggerDebugEnabled = NATURAL_ID_LOGGER.isDebugEnabled(); + for ( Object id : cachedResolutions ) { + final EntityKey entityKey = session.generateEntityKey( id, entityPersister ); + final Object entity = persistenceContext.getEntity( entityKey ); + final EntityEntry entry = persistenceContext.getEntry( entity ); + if ( entry != null ) { + if ( entry.requiresDirtyCheck( entity ) + // MANAGED is the only status we care about here + && entry.getStatus() == Status.MANAGED ) { + persistenceContext.getNaturalIdResolutions() + .handleSynchronization( id, entity, entityPersister ); + } + } + else { + // no entry + if ( loggerDebugEnabled ) { + NATURAL_ID_LOGGER.debugf( + "Cached natural-id/pk resolution linked to missing EntityEntry in persistence context: %s#%s", + entityMappingType.getEntityName(), + id + ); + } } - continue; - } - - if ( !entry.requiresDirtyCheck( entity ) ) { - continue; - } - - // MANAGED is the only status we care about here... - if ( entry.getStatus() != Status.MANAGED ) { - continue; } - - persistenceContext.getNaturalIdResolutions().handleSynchronization( pk, entity, entityPersister ); } } - } diff --git a/hibernate-core/src/main/java/org/hibernate/loader/ast/internal/AbstractNaturalIdLoader.java b/hibernate-core/src/main/java/org/hibernate/loader/ast/internal/AbstractNaturalIdLoader.java index ca4431b94e3d..325e769edad4 100644 --- a/hibernate-core/src/main/java/org/hibernate/loader/ast/internal/AbstractNaturalIdLoader.java +++ b/hibernate-core/src/main/java/org/hibernate/loader/ast/internal/AbstractNaturalIdLoader.java @@ -4,12 +4,11 @@ */ package org.hibernate.loader.ast.internal; +import java.util.Arrays; import java.util.List; import java.util.Locale; import java.util.function.BiConsumer; -import java.util.function.BiFunction; import java.util.function.Consumer; -import java.util.function.Function; import org.hibernate.HibernateException; import org.hibernate.LockOptions; @@ -24,6 +23,7 @@ import org.hibernate.metamodel.mapping.SelectableMapping; import org.hibernate.query.internal.SimpleQueryOptions; import org.hibernate.query.spi.QueryOptions; +import org.hibernate.query.sqm.ComparisonOperator; import org.hibernate.spi.NavigablePath; import org.hibernate.sql.ast.spi.SimpleFromClauseAccessImpl; import org.hibernate.sql.ast.spi.SqlAliasBaseManager; @@ -32,12 +32,16 @@ import org.hibernate.sql.ast.tree.expression.JdbcParameter; import org.hibernate.sql.ast.tree.from.TableGroup; import org.hibernate.sql.ast.tree.from.TableReference; +import org.hibernate.sql.ast.tree.predicate.ComparisonPredicate; +import org.hibernate.sql.ast.tree.predicate.NullnessPredicate; import org.hibernate.sql.ast.tree.predicate.Predicate; import org.hibernate.sql.ast.tree.select.QuerySpec; import org.hibernate.sql.ast.tree.select.SelectStatement; import org.hibernate.sql.exec.internal.BaseExecutionContext; import org.hibernate.sql.exec.internal.CallbackImpl; +import org.hibernate.sql.exec.internal.JdbcParameterBindingImpl; import org.hibernate.sql.exec.internal.JdbcParameterBindingsImpl; +import org.hibernate.sql.exec.internal.JdbcParameterImpl; import org.hibernate.sql.exec.spi.Callback; import org.hibernate.sql.exec.spi.JdbcOperationQuerySelect; import org.hibernate.sql.exec.spi.JdbcParameterBinding; @@ -47,9 +51,12 @@ import org.hibernate.sql.results.graph.internal.ImmutableFetchList; import org.hibernate.sql.results.internal.RowTransformerSingularReturnImpl; import org.hibernate.sql.results.spi.ListResultsConsumer; +import org.hibernate.stat.spi.StatisticsImplementor; import static java.util.Collections.emptyList; import static java.util.Collections.singletonList; +import static org.hibernate.engine.internal.NaturalIdLogging.NATURAL_ID_LOGGER; +import static org.hibernate.engine.internal.NaturalIdLogging.NATURAL_ID_MESSAGE_LOGGER; /** * Base support for {@link NaturalIdLoader} implementations @@ -86,14 +93,16 @@ public EntityMappingType getLoadable() { public T load(Object naturalIdValue, NaturalIdLoadOptions options, SharedSessionContractImplementor session) { final SessionFactoryImplementor factory = session.getFactory(); - final LockOptions lockOptions = options.getLockOptions() == null ? LockOptions.NONE : options.getLockOptions(); + final LockOptions lockOptions = + options.getLockOptions() == null + ? LockOptions.NONE + : options.getLockOptions(); final SelectStatement sqlSelect = LoaderSelectBuilder.createSelect( getLoadable(), - // null here means to select everything - null, + null, // null here means to select everything true, - emptyList(), // we're going to add the restrictions ourselves + emptyList(), // we're going to add the restrictions ourselves null, 1, session.getLoadQueryInfluencers(), @@ -102,15 +111,15 @@ public T load(Object naturalIdValue, NaturalIdLoadOptions options, SharedSession factory ); - // we have to add the restrictions ourselves manually because we want special null handling - final JdbcParameterBindings bindings = new JdbcParameterBindingsImpl( naturalIdMapping.getJdbcTypeCount() ); - applyNaturalIdRestriction( - naturalIdMapping().normalizeInput( naturalIdValue ), - sqlSelect.getQuerySpec().getFromClause().getRoots().get(0), - sqlSelect.getQuerySpec()::applyPredicate, - bindings::addBinding, + final QuerySpec querySpec = sqlSelect.getQuerySpec(); + return executeNaturalIdQuery( + naturalIdValue, + lockOptions, + sqlSelect, + querySpec.getFromClause().getRoots().get(0), + querySpec::applyPredicate, new LoaderSqlAstCreationState( - sqlSelect.getQuerySpec(), + querySpec, new SqlAliasBaseManager(), new SimpleFromClauseAccessImpl(), lockOptions, @@ -121,63 +130,57 @@ public T load(Object naturalIdValue, NaturalIdLoadOptions options, SharedSession ), session ); + } - final QueryOptions queryOptions = new SimpleQueryOptions( lockOptions, false ); - final JdbcOperationQuerySelect jdbcSelect = - factory.getJdbcServices().getJdbcEnvironment().getSqlAstTranslatorFactory() - .buildSelectTranslator( factory, sqlSelect ) - .translate( bindings, queryOptions ); - - final long startToken = factory.getStatistics().isStatisticsEnabled() ? System.nanoTime() : -1; - - final List results = session.getFactory().getJdbcServices().getJdbcSelectExecutor().list( - jdbcSelect, - bindings, - new NaturalIdLoaderWithOptionsExecutionContext( session, queryOptions ), - RowTransformerSingularReturnImpl.instance(), - null, - ListResultsConsumer.UniqueSemantic.FILTER, - 1 - ); + /** + * Apply restriction necessary to match the given natural-id value. + * Should also apply any predicates to the predicate consumer and + * any parameter / binding pairs. + */ + protected abstract void applyNaturalIdRestriction( + Object bindValue, + TableGroup rootTableGroup, + Consumer predicateConsumer, + BiConsumer jdbcParameterConsumer, + LoaderSqlAstCreationState sqlAstCreationState, + SharedSessionContractImplementor session); - if ( results.size() > 1 ) { - throw new HibernateException( + /** + * Helper to resolve ColumnReferences + */ + protected Expression resolveColumnReference( + TableGroup rootTableGroup, + SelectableMapping selectableMapping, + SqlExpressionResolver sqlExpressionResolver) { + final TableReference tableReference = + rootTableGroup.getTableReference( rootTableGroup.getNavigablePath(), + selectableMapping.getContainingTableExpression() ); + if ( tableReference == null ) { + throw new IllegalStateException( String.format( - "Loading by natural-id returned more that one row : %s", - entityDescriptor.getEntityName() + Locale.ROOT, + "Unable to locate TableReference for '%s' : %s", + selectableMapping.getContainingTableExpression(), + rootTableGroup ) ); } + return sqlExpressionResolver.resolveSqlExpression( tableReference, selectableMapping ); + } - final T result = results.isEmpty() ? null : results.get(0); -// entityDescriptor().getPostLoadListener().completedLoad( result, entityDescriptor(), naturalIdValue, KeyType.NATURAL_ID, LoadSource.DATABASE ); - if ( startToken > 0 ) { - session.getFactory().getStatistics().naturalIdQueryExecuted( - entityDescriptor().getEntityPersister().getRootEntityName(), - System.nanoTime() - startToken + @Override + public Object resolveNaturalIdToId(Object naturalIdValue, SharedSessionContractImplementor session) { + if ( NATURAL_ID_LOGGER.isTraceEnabled() ) { + NATURAL_ID_MESSAGE_LOGGER.retrievingIdForNaturalId( + entityDescriptor.getEntityName(), + naturalIdValue instanceof Object[] array + ? Arrays.toString( array ) + : naturalIdValue ); -// // todo (6.0) : need a "load-by-natural-id" stat, e.g., -// // final Object identifier = entityDescriptor().getIdentifierMapping().getIdentifier( result, session ); -// // session.getFactory().getStatistics().entityLoadedByNaturalId( entityDescriptor(), identifier ); } - return result; - } - /** - * Perform a select, restricted by natural-id, based on `domainResultProducer` and `fetchProcessor` - */ - protected L selectByNaturalId( - Object bindValue, - NaturalIdLoadOptions options, - BiFunction> domainResultProducer, - LoaderSqlAstCreationState.FetchProcessor fetchProcessor, - Function statementStartHandler, - BiConsumer statementCompletionHandler, - SharedSessionContractImplementor session) { final SessionFactoryImplementor factory = session.getFactory(); - final LockOptions lockOptions = options.getLockOptions() != null ? options.getLockOptions() : LockOptions.NONE; - final NavigablePath entityPath = new NavigablePath( entityDescriptor.getRootPathName() ); final QuerySpec rootQuerySpec = new QuerySpec( true ); @@ -185,8 +188,8 @@ protected L selectByNaturalId( rootQuerySpec, new SqlAliasBaseManager(), new SimpleFromClauseAccessImpl(), - lockOptions, - fetchProcessor, + LockOptions.NONE, + (fetchParent, creationState) -> ImmutableFetchList.EMPTY, true, new LoadQueryInfluencers( factory ), factory.getSqlTranslationEngine() @@ -204,132 +207,106 @@ protected L selectByNaturalId( rootQuerySpec.getFromClause().addRoot( rootTableGroup ); sqlAstCreationState.getFromClauseAccess().registerTableGroup( entityPath, rootTableGroup ); - final DomainResult domainResult = domainResultProducer.apply( rootTableGroup, sqlAstCreationState ); + final DomainResult domainResult = + entityDescriptor.getIdentifierMapping().createDomainResult( + rootTableGroup.getNavigablePath() + .append( EntityIdentifierMapping.ID_ROLE_NAME ), + rootTableGroup, + null, + sqlAstCreationState + ); - final SelectStatement sqlSelect = new SelectStatement( rootQuerySpec, singletonList( domainResult ) ); + return executeNaturalIdQuery( + naturalIdValue, + LockOptions.NONE, + new SelectStatement( rootQuerySpec, singletonList( domainResult ) ), + rootTableGroup, + rootQuerySpec::applyPredicate, + sqlAstCreationState, + session + ); + } - final JdbcParameterBindings bindings = new JdbcParameterBindingsImpl( naturalIdMapping.getJdbcTypeCount() ); + protected R executeNaturalIdQuery( + Object naturalIdValue, + LockOptions lockOptions, + SelectStatement sqlSelect, + TableGroup rootTableGroup, + Consumer predicateConsumer, + LoaderSqlAstCreationState sqlAstCreationState, + SharedSessionContractImplementor session) { + final SessionFactoryImplementor factory = session.getFactory(); + final JdbcParameterBindings bindings = + new JdbcParameterBindingsImpl( naturalIdMapping.getJdbcTypeCount() ); applyNaturalIdRestriction( - bindValue, + naturalIdMapping().normalizeInput( naturalIdValue ), rootTableGroup, - rootQuerySpec::applyPredicate, + predicateConsumer, bindings::addBinding, sqlAstCreationState, session ); final QueryOptions queryOptions = new SimpleQueryOptions( lockOptions, false ); - final JdbcOperationQuerySelect jdbcSelect = - factory.getJdbcServices().getJdbcEnvironment().getSqlAstTranslatorFactory() - .buildSelectTranslator( factory, sqlSelect ) - .translate( bindings, queryOptions ); - - final Long startToken = statementStartHandler.apply( factory.getStatistics().isStatisticsEnabled() ); - - final List results = factory.getJdbcServices().getJdbcSelectExecutor().list( - jdbcSelect, - bindings, - new NaturalIdLoaderWithOptionsExecutionContext( session, queryOptions ), - RowTransformerSingularReturnImpl.instance(), - null, - ListResultsConsumer.UniqueSemantic.FILTER, - 1 - ); + final var jdbcSelect = createJdbcOperationQuerySelect( sqlSelect, factory, bindings, queryOptions ); - if ( results.size() > 1 ) { - throw new HibernateException( - String.format( - "Loading by natural-id returned more that one row : %s", - entityDescriptor.getEntityName() - ) - ); - } + final StatisticsImplementor statistics = factory.getStatistics(); + final boolean statisticsEnabled = statistics.isStatisticsEnabled(); + final long startTime = statisticsEnabled ? System.nanoTime() : -1L; - final L result = results.isEmpty() ? null : results.get(0); - statementCompletionHandler.accept( result, startToken ); - return result; - } + final List results = + factory.getJdbcServices().getJdbcSelectExecutor() + .list( + jdbcSelect, + bindings, + new NaturalIdLoaderWithOptionsExecutionContext( session, queryOptions ), + RowTransformerSingularReturnImpl.instance(), + null, + ListResultsConsumer.UniqueSemantic.FILTER, + 1 + ); - /** - * Apply restriction necessary to match the given natural-id value. Should - * apply any predicates to `predicateConsumer` as well and any parameter / binding - * pairs - */ - protected abstract void applyNaturalIdRestriction( - Object bindValue, - TableGroup rootTableGroup, - Consumer predicateConsumer, - BiConsumer jdbcParameterConsumer, - LoaderSqlAstCreationState sqlAstCreationState, - SharedSessionContractImplementor session); + if ( statisticsEnabled ) { + statistics.naturalIdQueryExecuted( + entityDescriptor().getEntityPersister().getRootEntityName(), + System.nanoTime() - startTime + ); + } - /** - * Helper to resolve ColumnReferences - */ - protected Expression resolveColumnReference( - TableGroup rootTableGroup, - SelectableMapping selectableMapping, - SqlExpressionResolver sqlExpressionResolver, - @SuppressWarnings("unused") SessionFactoryImplementor sessionFactory) { - final TableReference tableReference = - rootTableGroup.getTableReference( rootTableGroup.getNavigablePath(), - selectableMapping.getContainingTableExpression() ); - if ( tableReference == null ) { - throw new IllegalStateException( + return switch ( results.size() ) { + case 0 -> null; + case 1 -> results.get( 0 ); + default -> throw new HibernateException( String.format( - Locale.ROOT, - "Unable to locate TableReference for `%s` : %s", - selectableMapping.getContainingTableExpression(), - rootTableGroup + "Query by natural id returned more that one row: %s", + entityDescriptor.getEntityName() ) ); - } - return sqlExpressionResolver.resolveSqlExpression( tableReference, selectableMapping ); + }; } - @Override - public Object resolveNaturalIdToId(Object naturalIdValue, SharedSessionContractImplementor session) { - return selectByNaturalId( - naturalIdMapping().normalizeInput( naturalIdValue ), - NaturalIdLoadOptions.NONE, - (tableGroup, creationState) -> entityDescriptor.getIdentifierMapping().createDomainResult( - tableGroup.getNavigablePath().append( EntityIdentifierMapping.ID_ROLE_NAME ), - tableGroup, - null, - creationState - ), - (fetchParent, creationState) -> ImmutableFetchList.EMPTY, - (statsEnabled) -> { -// entityDescriptor().getPreLoadListener().startingLoad( entityDescriptor, naturalIdValue, KeyType.NATURAL_ID, LoadSource.DATABASE ); - return statsEnabled ? System.nanoTime() : -1L; - }, - (result, startToken) -> { -// entityDescriptor().getPostLoadListener().completedLoad( result, entityDescriptor(), naturalIdValue, KeyType.NATURAL_ID, LoadSource.DATABASE ); - if ( startToken > 0 ) { - session.getFactory().getStatistics().naturalIdQueryExecuted( - entityDescriptor().getEntityPersister().getRootEntityName(), - System.nanoTime() - startToken - ); -// // todo (6.0) : need a "load-by-natural-id" stat -// // e.g., -// // final Object identifier = entityDescriptor().getIdentifierMapping().getIdentifier( result, session ); -// // session.getFactory().getStatistics().entityLoadedByNaturalId( entityDescriptor(), identifier ); - } - }, - session - ); + private static JdbcOperationQuerySelect createJdbcOperationQuerySelect( + SelectStatement sqlSelect, + SessionFactoryImplementor factory, + JdbcParameterBindings bindings, + QueryOptions queryOptions) { + return factory.getJdbcServices().getJdbcEnvironment() + .getSqlAstTranslatorFactory() + .buildSelectTranslator( factory, sqlSelect ) + .translate( bindings, queryOptions ); } @Override public Object resolveIdToNaturalId(Object id, SharedSessionContractImplementor session) { final SessionFactoryImplementor factory = session.getFactory(); + final EntityIdentifierMapping identifierMapping = entityDescriptor().getIdentifierMapping(); final JdbcParametersList.Builder builder = JdbcParametersList.newBuilder(); final SelectStatement sqlSelect = LoaderSelectBuilder.createSelect( entityDescriptor(), singletonList( naturalIdMapping() ), - entityDescriptor().getIdentifierMapping(), + identifierMapping, null, 1, session.getLoadQueryInfluencers(), @@ -339,37 +316,29 @@ public Object resolveIdToNaturalId(Object id, SharedSessionContractImplementor s ); final JdbcParametersList jdbcParameters = builder.build(); final JdbcParameterBindings bindings = new JdbcParameterBindingsImpl( jdbcParameters.size() ); - final int offset = bindings.registerParametersForEachJdbcValue( - id, - entityDescriptor().getIdentifierMapping(), - jdbcParameters, - session - ); + final int offset = bindings.registerParametersForEachJdbcValue( id, identifierMapping, jdbcParameters, session ); assert offset == jdbcParameters.size(); - final JdbcOperationQuerySelect jdbcSelect = - factory.getJdbcServices().getJdbcEnvironment().getSqlAstTranslatorFactory() - .buildSelectTranslator( factory, sqlSelect ) - .translate( bindings, QueryOptions.NONE ); - - final List results = + final List results = factory.getJdbcServices().getJdbcSelectExecutor() .list( - jdbcSelect, + createJdbcOperationQuerySelect( sqlSelect, factory, bindings, QueryOptions.NONE ), bindings, new NoCallbackExecutionContext( session ), - // because we select the natural-id we want to "reduce" the result + // because we select the natural id, + // we want to "reduce" the result RowTransformerSingularReturnImpl.instance(), null, ListResultsConsumer.UniqueSemantic.FILTER, 1 ); + return switch ( results.size() ) { case 0 -> null; case 1 -> results.get( 0 ); default -> throw new HibernateException( String.format( - "Resolving id to natural-id returned more that one row : %s #%s", + "Resolving id to natural id returned more that one row: %s #%s", entityDescriptor().getEntityName(), id ) @@ -377,6 +346,28 @@ public Object resolveIdToNaturalId(Object id, SharedSessionContractImplementor s }; } + void applyRestriction( + TableGroup rootTableGroup, + Consumer predicateConsumer, + BiConsumer jdbcParameterConsumer, + Object jdbcValue, + SelectableMapping jdbcValueMapping, + SqlExpressionResolver expressionResolver) { + final Expression columnReference = + resolveColumnReference( rootTableGroup, jdbcValueMapping, expressionResolver ); + if ( jdbcValue == null ) { + predicateConsumer.accept( new NullnessPredicate( columnReference ) ); + } + else { + final JdbcParameter jdbcParameter = new JdbcParameterImpl( jdbcValueMapping.getJdbcMapping() ); + final ComparisonPredicate predicate = + new ComparisonPredicate( columnReference, ComparisonOperator.EQUAL, jdbcParameter ); + predicateConsumer.accept( predicate ); + jdbcParameterConsumer.accept( jdbcParameter, + new JdbcParameterBindingImpl( jdbcValueMapping.getJdbcMapping(), jdbcValue ) ); + } + } + private static class NaturalIdLoaderWithOptionsExecutionContext extends BaseExecutionContext { private final Callback callback; @@ -397,6 +388,5 @@ public QueryOptions getQueryOptions() { public Callback getCallback() { return callback; } - } } diff --git a/hibernate-core/src/main/java/org/hibernate/loader/ast/internal/CompoundNaturalIdLoader.java b/hibernate-core/src/main/java/org/hibernate/loader/ast/internal/CompoundNaturalIdLoader.java index b4bad8336496..27b0b9d79728 100644 --- a/hibernate-core/src/main/java/org/hibernate/loader/ast/internal/CompoundNaturalIdLoader.java +++ b/hibernate-core/src/main/java/org/hibernate/loader/ast/internal/CompoundNaturalIdLoader.java @@ -4,25 +4,17 @@ */ package org.hibernate.loader.ast.internal; -import java.util.List; import java.util.function.BiConsumer; import java.util.function.Consumer; -import org.hibernate.engine.spi.SessionFactoryImplementor; import org.hibernate.engine.spi.SharedSessionContractImplementor; import org.hibernate.metamodel.mapping.EntityMappingType; -import org.hibernate.metamodel.mapping.SingularAttributeMapping; import org.hibernate.metamodel.mapping.internal.CompoundNaturalIdMapping; -import org.hibernate.query.sqm.ComparisonOperator; -import org.hibernate.sql.ast.spi.SqlExpressionResolver; import org.hibernate.sql.ast.tree.expression.Expression; import org.hibernate.sql.ast.tree.expression.JdbcParameter; import org.hibernate.sql.ast.tree.from.TableGroup; -import org.hibernate.sql.ast.tree.predicate.ComparisonPredicate; import org.hibernate.sql.ast.tree.predicate.NullnessPredicate; import org.hibernate.sql.ast.tree.predicate.Predicate; -import org.hibernate.sql.exec.internal.JdbcParameterBindingImpl; -import org.hibernate.sql.exec.internal.JdbcParameterImpl; import org.hibernate.sql.exec.spi.JdbcParameterBinding; /** @@ -44,58 +36,33 @@ protected void applyNaturalIdRestriction( BiConsumer jdbcParameterConsumer, LoaderSqlAstCreationState sqlAstCreationState, SharedSessionContractImplementor session) { - final SqlExpressionResolver sqlExpressionResolver = sqlAstCreationState.getSqlExpressionResolver(); - final SessionFactoryImplementor factory = session.getFactory(); - + final var expressionResolver = sqlAstCreationState.getSqlExpressionResolver(); if ( bindValue == null ) { - final List naturalIdAttributes = naturalIdMapping().getNaturalIdAttributes(); - for ( int i = 0; i < naturalIdAttributes.size(); i++ ) { - naturalIdAttributes.get( i ).forEachSelectable( + for ( var naturalIdAttribute : naturalIdMapping().getNaturalIdAttributes() ) { + naturalIdAttribute.forEachSelectable( (index, selectable) -> { - final Expression columnRef = resolveColumnReference( - rootTableGroup, - selectable, - sqlExpressionResolver, - factory - ); - predicateConsumer.accept( new NullnessPredicate( columnRef ) ); + final Expression columnReference = + resolveColumnReference( rootTableGroup, selectable, expressionResolver ); + predicateConsumer.accept( new NullnessPredicate( columnReference ) ); } ); } - - // EARLY EXIT!! - return; } - - naturalIdMapping().breakDownJdbcValues( - bindValue, - (valueIndex, jdbcValue, jdbcValueMapping) -> { - final Expression columnReference = resolveColumnReference( - rootTableGroup, - jdbcValueMapping, - sqlExpressionResolver, - factory - ); - - if ( jdbcValue == null ) { - predicateConsumer.accept( new NullnessPredicate( columnReference ) ); - } - else { - final JdbcParameter jdbcParameter = new JdbcParameterImpl( jdbcValueMapping.getJdbcMapping() ); - final ComparisonPredicate predicate = new ComparisonPredicate( - columnReference, - ComparisonOperator.EQUAL, - jdbcParameter - ); - predicateConsumer.accept( predicate ); - jdbcParameterConsumer.accept( - jdbcParameter, - new JdbcParameterBindingImpl( jdbcValueMapping.getJdbcMapping(), jdbcValue ) - ); - } - }, - session - ); + else { + naturalIdMapping().breakDownJdbcValues( + bindValue, + (valueIndex, jdbcValue, jdbcValueMapping) -> + applyRestriction( + rootTableGroup, + predicateConsumer, + jdbcParameterConsumer, + jdbcValue, + jdbcValueMapping, + expressionResolver + ), + session + ); + } } } diff --git a/hibernate-core/src/main/java/org/hibernate/loader/ast/internal/LoaderHelper.java b/hibernate-core/src/main/java/org/hibernate/loader/ast/internal/LoaderHelper.java index 6870ef17b519..6aad19c69c4f 100644 --- a/hibernate-core/src/main/java/org/hibernate/loader/ast/internal/LoaderHelper.java +++ b/hibernate-core/src/main/java/org/hibernate/loader/ast/internal/LoaderHelper.java @@ -4,7 +4,6 @@ */ package org.hibernate.loader.ast.internal; -import java.lang.reflect.Array; import java.util.List; import org.hibernate.Hibernate; @@ -23,12 +22,10 @@ import org.hibernate.event.monitor.spi.DiagnosticEvent; import org.hibernate.internal.OptimisticLockHelper; import org.hibernate.internal.build.AllowReflection; -import org.hibernate.loader.LoaderLogging; import org.hibernate.metamodel.mapping.BasicValuedModelPart; import org.hibernate.metamodel.mapping.EntityMappingType; import org.hibernate.metamodel.mapping.JdbcMapping; import org.hibernate.persister.entity.EntityPersister; -import org.hibernate.pretty.MessageHelper; import org.hibernate.sql.ast.tree.expression.JdbcParameter; import org.hibernate.sql.ast.tree.select.SelectStatement; import org.hibernate.sql.exec.internal.JdbcParameterBindingImpl; @@ -40,6 +37,10 @@ import org.hibernate.sql.results.spi.ListResultsConsumer; import org.hibernate.type.descriptor.java.JavaType; +import static java.lang.reflect.Array.newInstance; +import static org.hibernate.loader.LoaderLogging.LOADER_LOGGER; +import static org.hibernate.pretty.MessageHelper.infoString; + /** * @author Steve Ebersole */ @@ -70,9 +71,9 @@ public static void upgradeLock( ); } - if ( LoaderLogging.LOADER_LOGGER.isTraceEnabled() ) { - LoaderLogging.LOADER_LOGGER.tracef( - "Locking `%s( %s )` in `%s` lock-mode", + if ( LOADER_LOGGER.isTraceEnabled() ) { + LOADER_LOGGER.tracef( + "Locking %s with id '%s' in mode %s", persister.getEntityName(), entry.getId(), requestedLockMode @@ -99,7 +100,7 @@ public static void upgradeLock( else { throw new IllegalStateException( String.format( "Trying to lock versioned entity %s but found null version", - MessageHelper.infoString( persister.getEntityName(), entry.getId() ) + infoString( persister.getEntityName(), entry.getId() ) ) ); } } @@ -204,7 +205,7 @@ public static K[] normalizeKeys( @AllowReflection public static X[] createTypedArray(Class elementClass, @SuppressWarnings("SameParameterValue") int length) { //noinspection unchecked - return (X[]) Array.newInstance( elementClass, length ); + return (X[]) newInstance( elementClass, length ); } /** diff --git a/hibernate-core/src/main/java/org/hibernate/loader/ast/internal/SimpleNaturalIdLoader.java b/hibernate-core/src/main/java/org/hibernate/loader/ast/internal/SimpleNaturalIdLoader.java index 8d583544c5cd..c495c0bd463a 100644 --- a/hibernate-core/src/main/java/org/hibernate/loader/ast/internal/SimpleNaturalIdLoader.java +++ b/hibernate-core/src/main/java/org/hibernate/loader/ast/internal/SimpleNaturalIdLoader.java @@ -9,16 +9,13 @@ import org.hibernate.engine.spi.SharedSessionContractImplementor; import org.hibernate.metamodel.mapping.EntityMappingType; +import org.hibernate.metamodel.mapping.SingularAttributeMapping; import org.hibernate.metamodel.mapping.internal.SimpleNaturalIdMapping; -import org.hibernate.query.sqm.ComparisonOperator; import org.hibernate.sql.ast.tree.expression.Expression; import org.hibernate.sql.ast.tree.expression.JdbcParameter; import org.hibernate.sql.ast.tree.from.TableGroup; -import org.hibernate.sql.ast.tree.predicate.ComparisonPredicate; import org.hibernate.sql.ast.tree.predicate.NullnessPredicate; import org.hibernate.sql.ast.tree.predicate.Predicate; -import org.hibernate.sql.exec.internal.JdbcParameterBindingImpl; -import org.hibernate.sql.exec.internal.JdbcParameterImpl; import org.hibernate.sql.exec.spi.JdbcParameterBinding; /** @@ -45,46 +42,29 @@ protected void applyNaturalIdRestriction( BiConsumer jdbcParameterConsumer, LoaderSqlAstCreationState sqlAstCreationState, SharedSessionContractImplementor session) { + final var expressionResolver = sqlAstCreationState.getSqlExpressionResolver(); + final SingularAttributeMapping naturalIdMapping = naturalIdMapping().getAttribute(); if ( bindValue == null ) { - naturalIdMapping().getAttribute().forEachSelectable( + naturalIdMapping.forEachSelectable( (index, selectable) -> { - final Expression columnReference = resolveColumnReference( - rootTableGroup, - selectable, - sqlAstCreationState.getSqlExpressionResolver(), - session.getFactory() - ); + final Expression columnReference = + resolveColumnReference( rootTableGroup, selectable, expressionResolver ); predicateConsumer.accept( new NullnessPredicate( columnReference ) ); } ); } else { - naturalIdMapping().getAttribute().breakDownJdbcValues( + naturalIdMapping.breakDownJdbcValues( bindValue, - (valueIndex, jdbcValue, jdbcValueMapping) -> { - final Expression columnReference = resolveColumnReference( - rootTableGroup, - jdbcValueMapping, - sqlAstCreationState.getSqlExpressionResolver(), - session.getFactory() - ); - if ( jdbcValue == null ) { - predicateConsumer.accept( new NullnessPredicate( columnReference ) ); - } - else { - final JdbcParameter jdbcParameter = new JdbcParameterImpl( jdbcValueMapping.getJdbcMapping() ); - final ComparisonPredicate predicate = new ComparisonPredicate( - columnReference, - ComparisonOperator.EQUAL, - jdbcParameter - ); - predicateConsumer.accept( predicate ); - jdbcParameterConsumer.accept( - jdbcParameter, - new JdbcParameterBindingImpl( jdbcValueMapping.getJdbcMapping(), jdbcValue ) - ); - } - }, + (valueIndex, jdbcValue, jdbcValueMapping) -> + applyRestriction( + rootTableGroup, + predicateConsumer, + jdbcParameterConsumer, + jdbcValue, + jdbcValueMapping, + expressionResolver + ), session ); } diff --git a/hibernate-core/src/main/java/org/hibernate/loader/internal/BaseNaturalIdLoadAccessImpl.java b/hibernate-core/src/main/java/org/hibernate/loader/internal/BaseNaturalIdLoadAccessImpl.java index 223078388a3d..c62a5d31060a 100644 --- a/hibernate-core/src/main/java/org/hibernate/loader/internal/BaseNaturalIdLoadAccessImpl.java +++ b/hibernate-core/src/main/java/org/hibernate/loader/internal/BaseNaturalIdLoadAccessImpl.java @@ -24,7 +24,6 @@ import org.hibernate.engine.spi.Status; import org.hibernate.graph.GraphSemantic; import org.hibernate.graph.spi.RootGraphImplementor; -import org.hibernate.loader.LoaderLogging; import org.hibernate.loader.ast.spi.NaturalIdLoadOptions; import org.hibernate.metamodel.mapping.EntityMappingType; import org.hibernate.persister.entity.EntityPersister; @@ -35,7 +34,7 @@ import static org.hibernate.internal.NaturalIdHelper.performAnyNeededCrossReferenceSynchronizations; /** - * Base support for load-by-natural-id + * Base support for loading by {@linkplain org.hibernate.annotations.NaturalId natural id}. * * @author Steve Ebersole */ @@ -141,68 +140,56 @@ protected void synchronizationEnabled(boolean synchronizationEnabled) { // : resolvedId; // } - @SuppressWarnings( "unchecked" ) - protected final T doGetReference(Object normalizedNaturalIdValue) { - performAnyNeededCrossReferenceSynchronizations( synchronizationEnabled, entityDescriptor, context.getSession() ); + private Object getCachedResolution(Object normalizedNaturalIdValue) { + final SessionImplementor session = context.getSession(); + + performAnyNeededCrossReferenceSynchronizations( synchronizationEnabled, entityDescriptor, session ); context.checkOpenOrWaitingForAutoClose(); context.pulseTransactionCoordinator(); - final SessionImplementor session = context.getSession(); - final PersistenceContext persistenceContext = session.getPersistenceContextInternal(); + return session.getPersistenceContextInternal() + .getNaturalIdResolutions() + .findCachedIdByNaturalId( normalizedNaturalIdValue, entityPersister() ); + } - final Object cachedResolution = - persistenceContext.getNaturalIdResolutions() - .findCachedIdByNaturalId( normalizedNaturalIdValue, entityPersister() ); + protected final T doGetReference(Object normalizedNaturalIdValue) { + final Object cachedResolution = getCachedResolution( normalizedNaturalIdValue ); if ( cachedResolution == INVALID_NATURAL_ID_REFERENCE ) { // the entity is deleted, although not yet flushed - return null return null; } + else if ( cachedResolution != null ) { + return identifierLoadAccess().getReference( cachedResolution ); + } else { - if ( cachedResolution != null ) { - return (T) getIdentifierLoadAccess().getReference( cachedResolution ); - } - else { - LoaderLogging.LOADER_LOGGER.tracef( - "Selecting entity identifier by natural-id for `#getReference` handling - %s : %s", - entityPersister().getEntityName(), - normalizedNaturalIdValue - ); - final Object idFromDatabase = - entityPersister().getNaturalIdLoader() - .resolveNaturalIdToId( normalizedNaturalIdValue, session ); - return idFromDatabase == null ? null : (T) getIdentifierLoadAccess().getReference( idFromDatabase ); - } + final Object idFromDatabase = + entityPersister().getNaturalIdLoader() + .resolveNaturalIdToId( normalizedNaturalIdValue, context.getSession() ); + return idFromDatabase == null ? null : identifierLoadAccess().getReference( idFromDatabase ); } } protected final T doLoad(Object normalizedNaturalIdValue) { - performAnyNeededCrossReferenceSynchronizations( synchronizationEnabled, entityDescriptor, context.getSession() ); - - context.checkOpenOrWaitingForAutoClose(); - context.pulseTransactionCoordinator(); - - final SessionImplementor session = context.getSession(); - final PersistenceContext persistenceContext = session.getPersistenceContextInternal(); - - final Object cachedResolution = - persistenceContext.getNaturalIdResolutions() - .findCachedIdByNaturalId( normalizedNaturalIdValue, entityPersister() ); + final Object cachedResolution = getCachedResolution( normalizedNaturalIdValue ); if ( cachedResolution == INVALID_NATURAL_ID_REFERENCE ) { return null; } else { + final SessionImplementor session = context.getSession(); final LoadQueryInfluencers influencers = session.getLoadQueryInfluencers(); - final HashSet fetchProfiles = + final var fetchProfiles = influencers.adjustFetchProfiles( disabledFetchProfiles, enabledFetchProfiles ); final EffectiveEntityGraph effectiveEntityGraph = session.getLoadQueryInfluencers().applyEntityGraph( rootGraph, graphSemantic); try { @SuppressWarnings("unchecked") final T loaded = cachedResolution != null - ? (T) getIdentifierLoadAccess().load(cachedResolution) - : (T) entityPersister().getNaturalIdLoader().load( normalizedNaturalIdValue, this, session ); + ? identifierLoadAccess().load(cachedResolution) + : (T) entityPersister().getNaturalIdLoader() + .load( normalizedNaturalIdValue, this, session ); if ( loaded != null ) { + final PersistenceContext persistenceContext = session.getPersistenceContextInternal(); final LazyInitializer lazyInitializer = HibernateProxy.extractLazyInitializer( loaded ); final EntityEntry entry = lazyInitializer != null ? persistenceContext.getEntry( lazyInitializer.getImplementation() ) @@ -222,8 +209,9 @@ protected final T doLoad(Object normalizedNaturalIdValue) { } } - protected final IdentifierLoadAccess getIdentifierLoadAccess() { - final IdentifierLoadAccessImpl loadAccess = new IdentifierLoadAccessImpl<>( context, entityPersister() ); + protected final IdentifierLoadAccess identifierLoadAccess() { + final IdentifierLoadAccessImpl loadAccess = + new IdentifierLoadAccessImpl<>( context, entityPersister() ); if ( lockOptions != null ) { loadAccess.with( lockOptions ); } diff --git a/hibernate-core/src/main/java/org/hibernate/loader/internal/NaturalIdLoadAccessImpl.java b/hibernate-core/src/main/java/org/hibernate/loader/internal/NaturalIdLoadAccessImpl.java index f18fee5dec69..db334b49403e 100644 --- a/hibernate-core/src/main/java/org/hibernate/loader/internal/NaturalIdLoadAccessImpl.java +++ b/hibernate-core/src/main/java/org/hibernate/loader/internal/NaturalIdLoadAccessImpl.java @@ -19,9 +19,14 @@ import java.util.Optional; /** + * Implementation of {@link NaturalIdLoadAccess}. + * * @author Steve Ebersole */ -public class NaturalIdLoadAccessImpl extends BaseNaturalIdLoadAccessImpl implements NaturalIdLoadAccess { +public class NaturalIdLoadAccessImpl + extends BaseNaturalIdLoadAccessImpl + implements NaturalIdLoadAccess { + private final Map naturalIdParameters = new LinkedHashMap<>(); public NaturalIdLoadAccessImpl(LoadAccessContext context, EntityMappingType entityDescriptor) { diff --git a/hibernate-core/src/main/java/org/hibernate/loader/internal/SimpleNaturalIdLoadAccessImpl.java b/hibernate-core/src/main/java/org/hibernate/loader/internal/SimpleNaturalIdLoadAccessImpl.java index d03f29d2d42f..f041771aaa06 100644 --- a/hibernate-core/src/main/java/org/hibernate/loader/internal/SimpleNaturalIdLoadAccessImpl.java +++ b/hibernate-core/src/main/java/org/hibernate/loader/internal/SimpleNaturalIdLoadAccessImpl.java @@ -18,31 +18,27 @@ import org.hibernate.LockOptions; import org.hibernate.SimpleNaturalIdLoadAccess; import org.hibernate.graph.GraphSemantic; -import org.hibernate.loader.LoaderLogging; import org.hibernate.metamodel.mapping.EntityMappingType; import org.hibernate.metamodel.mapping.internal.SimpleNaturalIdMapping; /** + * Implementation of {@link SimpleNaturalIdLoadAccess}. + * + * @implNote We allow use of {@code SimpleNaturalIdLoadAccess} for + * composite natural ids with the assumption that we will be given + * a singular representation of the natural id (a map or array). + * * @author Steve Ebersole */ public class SimpleNaturalIdLoadAccessImpl extends BaseNaturalIdLoadAccessImpl implements SimpleNaturalIdLoadAccess { + private final boolean hasSimpleNaturalId; public SimpleNaturalIdLoadAccessImpl(LoadAccessContext context, EntityMappingType entityDescriptor) { super( context, entityDescriptor ); - hasSimpleNaturalId = entityDescriptor.getNaturalIdMapping() instanceof SimpleNaturalIdMapping; - - if ( !hasSimpleNaturalId ) { - // Just log it - we allow this for composite natural ids with the assumption - // that a singular representation of the natural id (Map or array) will be passed - LoaderLogging.LOADER_LOGGER.debugf( - "Entity [%s] did not define a simple natural id", - entityDescriptor.getEntityName() - ); - } } @Override @@ -107,7 +103,7 @@ private void verifySimplicity(Object naturalIdValue) { throw new HibernateException( String.format( Locale.ROOT, - "Cannot interpret natural-id value [%s] for compound natural-id: %s", + "Cannot interpret natural id value [%s] as compound natural id of entity '%s'", naturalIdValue, entityPersister().getEntityName() ) diff --git a/hibernate-core/src/main/java/org/hibernate/metamodel/mapping/internal/CompoundNaturalIdMapping.java b/hibernate-core/src/main/java/org/hibernate/metamodel/mapping/internal/CompoundNaturalIdMapping.java index 70d901c5b0cc..5c50957885bf 100644 --- a/hibernate-core/src/main/java/org/hibernate/metamodel/mapping/internal/CompoundNaturalIdMapping.java +++ b/hibernate-core/src/main/java/org/hibernate/metamodel/mapping/internal/CompoundNaturalIdMapping.java @@ -143,7 +143,7 @@ else if ( incoming instanceof Map valueMap ) { return values; } else { - throw new UnsupportedMappingException( "Could not normalize compound natural-id value: " + incoming ); + throw new UnsupportedMappingException( "Could not normalize compound natural id value: " + incoming ); } } diff --git a/hibernate-core/src/main/java/org/hibernate/persister/entity/AbstractEntityPersister.java b/hibernate-core/src/main/java/org/hibernate/persister/entity/AbstractEntityPersister.java index 93f7bdf3149a..7ed29090a152 100644 --- a/hibernate-core/src/main/java/org/hibernate/persister/entity/AbstractEntityPersister.java +++ b/hibernate-core/src/main/java/org/hibernate/persister/entity/AbstractEntityPersister.java @@ -4523,13 +4523,6 @@ public Object loadEntityIdByNaturalId( LockOptions lockOptions, SharedSessionContractImplementor session) { verifyHasNaturalId(); - if ( LOG.isTraceEnabled() ) { - LOG.tracef( - "Resolving natural-id [%s] to id : %s ", - Arrays.asList( naturalIdValues ), - infoString( this ) - ); - } return getNaturalIdLoader().resolveNaturalIdToId( naturalIdValues, session ); } From 4e9d3a8eccaf8ee664751d9af2dbede078e228a4 Mon Sep 17 00:00:00 2001 From: Gavin King Date: Sun, 13 Jul 2025 23:56:14 +0200 Subject: [PATCH 23/32] minor optimizations to logging and comments in event handlers --- .../AbstractFlushingEventListener.java | 4 +- .../internal/AbstractSaveEventListener.java | 88 ++++++++++--------- .../internal/DefaultMergeEventListener.java | 4 +- .../internal/DefaultPersistEventListener.java | 28 +++--- .../DefaultReplicateEventListener.java | 2 +- .../EntityCopyAllowedLoggedObserver.java | 26 ++---- .../event/internal/EvictVisitor.java | 7 +- 7 files changed, 74 insertions(+), 85 deletions(-) diff --git a/hibernate-core/src/main/java/org/hibernate/event/internal/AbstractFlushingEventListener.java b/hibernate-core/src/main/java/org/hibernate/event/internal/AbstractFlushingEventListener.java index 684b97970ba2..e967bc287574 100644 --- a/hibernate-core/src/main/java/org/hibernate/event/internal/AbstractFlushingEventListener.java +++ b/hibernate-core/src/main/java/org/hibernate/event/internal/AbstractFlushingEventListener.java @@ -121,13 +121,13 @@ protected void logFlushResults(FlushEvent event) { } /** - * process cascade save/update at the start of a flush to discover + * Process cascade save/update at the start of a flush to discover * any newly referenced entity that must be passed to saveOrUpdate(), * and also apply orphan delete */ private void prepareEntityFlushes(EventSource session, PersistenceContext persistenceContext) throws HibernateException { - LOG.debug( "Processing flush-time cascades" ); + LOG.trace( "Processing flush-time cascades" ); final PersistContext context = PersistContext.create(); // safe from concurrent modification because of how concurrentEntries() is implemented on IdentityMap for ( var me : persistenceContext.reentrantSafeEntityEntries() ) { diff --git a/hibernate-core/src/main/java/org/hibernate/event/internal/AbstractSaveEventListener.java b/hibernate-core/src/main/java/org/hibernate/event/internal/AbstractSaveEventListener.java index c9057a755015..3588f82641e7 100644 --- a/hibernate-core/src/main/java/org/hibernate/event/internal/AbstractSaveEventListener.java +++ b/hibernate-core/src/main/java/org/hibernate/event/internal/AbstractSaveEventListener.java @@ -43,7 +43,9 @@ import static org.hibernate.pretty.MessageHelper.infoString; /** - * A convenience base class for listeners responding to save events. + * A convenience base class for listeners responding to persist or merge events. + *

+ * This class contains common functionality for persisting new transient instances. * * @author Steve Ebersole. */ @@ -58,13 +60,13 @@ public void injectCallbackRegistry(CallbackRegistry callbackRegistry) { } /** - * Prepares the save call using the given requested id. + * Prepares the persist call using the given requested id. * - * @param entity The entity to be saved. - * @param requestedId The id to which to associate the entity. - * @param entityName The name of the entity being saved. - * @param context Generally cascade-specific information. - * @param source The session which is the source of this save event. + * @param entity The entity to be persisted + * @param requestedId The id with which to associate the entity + * @param entityName The name of the entity being persisted + * @param context Generally cascade-specific information + * @param source The session which is the source of this event * * @return The id used to save the entity. */ @@ -79,18 +81,18 @@ protected Object saveWithRequestedId( } /** - * Prepares the save call using a newly generated id. + * Prepares the persist call using a newly generated id. * - * @param entity The entity to be saved - * @param entityName The entity-name for the entity to be saved - * @param context Generally cascade-specific information. - * @param source The session which is the source of this save event. + * @param entity The entity to be persisted + * @param entityName The entity-name for the entity to be persisted + * @param context Generally cascade-specific information + * @param source The session which is the source of this persist event * @param requiresImmediateIdAccess does the event context require * access to the identifier immediately after execution of this method * (if not, post-insert style id generators may be postponed if we are * outside a transaction). * - * @return The id used to save the entity; may be null depending on the + * @return The id used to persist the entity; may be null depending on the * type of id generator used and the requiresImmediateIdAccess value */ protected Object saveWithGeneratedId( @@ -140,10 +142,10 @@ else if ( generatedBeforeExecution ) { * Generate an id before execution of the insert statements, * using the given {@link BeforeExecutionGenerator}. * - * @param entity The entity instance to be saved - * @param source The session which is the source of this save event. - * @param generator The entity's generator - * @param persister The entity's persister instance. + * @param entity The entity instance to be persisted + * @param source The session which is the source of this persist event + * @param generator The generator for the entity id + * @param persister The persister for the entity * * @return The generated id */ @@ -158,7 +160,7 @@ private static Object generateId( throw new IdentifierGenerationException( "Null id generated for entity '" + persister.getEntityName() + "'" ); } else { - if ( LOG.isDebugEnabled() ) { + if ( LOG.isTraceEnabled() ) { // TODO: define toString()s for generators LOG.tracef( "Generated identifier [%s] using generator '%s'", @@ -171,18 +173,18 @@ private static Object generateId( } /** - * Prepares the save call by checking the session caches for a pre-existing + * Prepares the persist call by checking the session caches for a pre-existing * entity and performing any lifecycle callbacks. * - * @param entity The entity to be saved. - * @param id The id by which to save the entity. - * @param persister The entity's persister instance. + * @param entity The entity to be persisted + * @param id The id by which to persist the entity + * @param persister The entity's persister instance * @param useIdentityColumn Is an identity column being used? - * @param context Generally cascade-specific information. - * @param source The session from which the event originated. + * @param context Generally cascade-specific information + * @param source The session from which the event originated * @param delayIdentityInserts Should the identity insert be delayed? * - * @return The id used to save the entity; may be null depending on the + * @return The id used to persist the entity; may be null depending on the * type of id generator used and on delayIdentityInserts */ protected Object performSave( @@ -211,7 +213,7 @@ protected Object performSave( } if ( LOG.isTraceEnabled() ) { - LOG.trace( "Saving " + infoString( persister, id, source.getFactory() ) ); + LOG.trace( "Persisting " + infoString( persister, id, source.getFactory() ) ); } final EntityKey key = useIdentityColumn ? null : entityKey( id, persister, source ); @@ -237,18 +239,18 @@ else if ( persistenceContext.containsDeletedUnloadedEntityKey( key ) ) { } /** - * Performs all the actual work needed to save an entity (well to get the save moved to - * the execution queue). + * Performs all the actual work needed to persist an entity + * (well to get the persist action moved to the execution queue). * - * @param entity The entity to be saved + * @param entity The entity to be persisted * @param key The id to be used for saving the entity (or null, in the case of identity columns) - * @param persister The entity's persister instance. + * @param persister The persister for the entity * @param useIdentityColumn Should an identity column be used for id generation? - * @param context Generally cascade-specific information. - * @param source The session which is the source of the current event. + * @param context Generally cascade-specific information + * @param source The session which is the source of the current event * @param delayIdentityInserts Should the identity insert be delayed? * - * @return The id used to save the entity; may be null depending on the + * @return The id used to persist the entity; may be null depending on the * type of id generator used and the requiresImmediateIdAccess value */ protected Object performSaveOrReplicate( @@ -394,10 +396,10 @@ protected Map getMergeMap(C anything) { } /** - * After the save, will the version number be incremented + * After the persist, will the version number be incremented * if the instance is modified? * - * @return True if the version will be incremented on an entity change after save; + * @return True if the version will be incremented on an entity change after persist; * false otherwise. */ protected boolean isVersionIncrementDisabled() { @@ -451,11 +453,11 @@ protected boolean substituteValuesIfNecessary( } /** - * Handles the calls needed to perform pre-save cascades for the given entity. + * Handles the calls needed to perform pre-persist cascades for the given entity. * - * @param source The session from which the save event originated. - * @param persister The entity's persister instance. - * @param entity The entity to be saved. + * @param source The session from which the persist event originated + * @param persister The persister for the entity + * @param entity The entity to be persisted * @param context Generally cascade-specific data */ protected void cascadeBeforeSave( @@ -482,11 +484,11 @@ protected void cascadeBeforeSave( } /** - * Handles calls needed to perform post-save cascades. + * Handles calls needed to perform post-persist cascades. * - * @param source The session from which the event originated. - * @param persister The entity's persister instance. - * @param entity The entity being saved. + * @param source The session from which the event originated + * @param persister The persister for the entity + * @param entity The entity being persisted * @param context Generally cascade-specific data */ protected void cascadeAfterSave( diff --git a/hibernate-core/src/main/java/org/hibernate/event/internal/DefaultMergeEventListener.java b/hibernate-core/src/main/java/org/hibernate/event/internal/DefaultMergeEventListener.java index 2b2d1db2ce99..c98ee56f5c7e 100644 --- a/hibernate-core/src/main/java/org/hibernate/event/internal/DefaultMergeEventListener.java +++ b/hibernate-core/src/main/java/org/hibernate/event/internal/DefaultMergeEventListener.java @@ -121,7 +121,7 @@ else if ( isPersistentAttributeInterceptable( original ) ) { final PersistentAttributeInterceptor interceptor = asPersistentAttributeInterceptable( original ).$$_hibernate_getInterceptor(); if ( interceptor instanceof EnhancementAsProxyLazinessInterceptor proxyInterceptor ) { - LOG.trace( "Ignoring uninitialized enhanced-proxy" ); + LOG.trace( "Ignoring uninitialized enhanced proxy" ); event.setResult( source.byId( proxyInterceptor.getEntityName() ) .getReference( proxyInterceptor.getIdentifier() ) ); } @@ -314,7 +314,7 @@ protected void entityIsTransient(MergeEvent event, Object id, MergeContext copyC // copy created before we actually copy super.cascadeAfterSave( session, persister, entity, copyCache ); - // this is the second pass through on a merge op, so here we limit the + // this is the second pass of a merge operation, so here we limit the // replacement to association types (value types were already replaced // during the first pass) // final Object[] newSourceValues = persister.getValues( entity ); diff --git a/hibernate-core/src/main/java/org/hibernate/event/internal/DefaultPersistEventListener.java b/hibernate-core/src/main/java/org/hibernate/event/internal/DefaultPersistEventListener.java index 38a0a62c7342..692b4ba1ed57 100644 --- a/hibernate-core/src/main/java/org/hibernate/event/internal/DefaultPersistEventListener.java +++ b/hibernate-core/src/main/java/org/hibernate/event/internal/DefaultPersistEventListener.java @@ -19,15 +19,15 @@ import org.hibernate.internal.CoreMessageLogger; import org.hibernate.jpa.event.spi.CallbackRegistryConsumer; import org.hibernate.persister.entity.EntityPersister; -import org.hibernate.pretty.MessageHelper; import org.hibernate.proxy.HibernateProxy; import org.hibernate.proxy.LazyInitializer; import static org.hibernate.event.internal.EntityState.getEntityState; +import static org.hibernate.pretty.MessageHelper.infoString; /** - * Defines the default create event listener used by hibernate for creating - * transient entities in response to generated create events. + * Defines the default event listener used by Hibernate for persisting + * transient entities in response to generated persist events. * * @author Gavin King */ @@ -53,9 +53,9 @@ public void onPersist(PersistEvent event) throws HibernateException { } /** - * Handle the given create event. + * Handle the given persist event. * - * @param event The create event to be handled. + * @param event The persist event to be handled * */ @Override @@ -83,7 +83,7 @@ private void persist(PersistEvent event, PersistContext createCache, Object enti final String entityName = entityName( event, entity, entityEntry ); switch ( getEntityState( entity, entityName, entityEntry, source, true ) ) { case DETACHED: - throw new PersistentObjectException( "detached entity passed to persist: " + throw new PersistentObjectException( "Detached entity passed to persist: " + EventUtil.getLoggableName( event.getEntityName(), entity) ); case PERSISTENT: entityIsPersistent( event, createCache ); @@ -99,7 +99,7 @@ private void persist(PersistEvent event, PersistContext createCache, Object enti break; default: throw new ObjectDeletedException( - "deleted entity passed to persist", + "Deleted entity passed to persist", null, EventUtil.getLoggableName( event.getEntityName(), entity ) ); @@ -135,13 +135,13 @@ private void justCascade(PersistContext createCache, EventSource source, Object } /** - * Handle the given create event. + * Handle the given persist event. * - * @param event The save event to be handled. - * @param createCache The copy cache of entity instance to merge/copy instance. + * @param event The persist event to be handled + * @param createCache The copy cache of entity instance to merge/copy instance */ protected void entityIsTransient(PersistEvent event, PersistContext createCache) { - LOG.trace( "Saving transient instance" ); + LOG.trace( "Persisting transient instance" ); final EventSource source = event.getSession(); final Object entity = source.getPersistenceContextInternal().unproxy( event.getObject() ); if ( createCache.add( entity ) ) { @@ -154,10 +154,8 @@ private void entityIsDeleted(PersistEvent event, PersistContext createCache) { final Object entity = source.getPersistenceContextInternal().unproxy( event.getObject() ); final EntityPersister persister = source.getEntityPersister( event.getEntityName(), entity ); if ( LOG.isTraceEnabled() ) { - LOG.tracef( - "un-scheduling entity deletion [%s]", - MessageHelper.infoString( persister, persister.getIdentifier( entity, source ), event.getFactory() ) - ); + final Object id = persister.getIdentifier( entity, source ); + LOG.trace( "Unscheduling entity deletion: " + infoString( persister, id, source.getFactory() ) ); } if ( createCache.add( entity ) ) { justCascade( createCache, source, entity, persister ); diff --git a/hibernate-core/src/main/java/org/hibernate/event/internal/DefaultReplicateEventListener.java b/hibernate-core/src/main/java/org/hibernate/event/internal/DefaultReplicateEventListener.java index 6446fb452119..b095ed0f6f52 100644 --- a/hibernate-core/src/main/java/org/hibernate/event/internal/DefaultReplicateEventListener.java +++ b/hibernate-core/src/main/java/org/hibernate/event/internal/DefaultReplicateEventListener.java @@ -97,7 +97,7 @@ private void doReplicate(ReplicateEvent event, EventSource source, Object entity performReplication( entity, id, realOldVersion, persister, replicationMode, source ); } else if ( LOG.isTraceEnabled() ) { - // do nothing (don't even re-associate object!) + // do nothing (don't even reassociate entity!) LOG.trace( "No need to replicate" ); } diff --git a/hibernate-core/src/main/java/org/hibernate/event/internal/EntityCopyAllowedLoggedObserver.java b/hibernate-core/src/main/java/org/hibernate/event/internal/EntityCopyAllowedLoggedObserver.java index 4593547e7650..198204284d13 100644 --- a/hibernate-core/src/main/java/org/hibernate/event/internal/EntityCopyAllowedLoggedObserver.java +++ b/hibernate-core/src/main/java/org/hibernate/event/internal/EntityCopyAllowedLoggedObserver.java @@ -15,7 +15,8 @@ import org.hibernate.internal.CoreLogging; import org.hibernate.internal.CoreMessageLogger; import org.hibernate.internal.util.collections.IdentitySet; -import org.hibernate.pretty.MessageHelper; + +import static org.hibernate.pretty.MessageHelper.infoString; /** * An {@link EntityCopyObserver} implementation that allows multiple representations of @@ -53,15 +54,10 @@ public void entityCopyDetected( Object mergeEntity2, EventSource session) { final String entityName = session.getEntityName( managedEntity ); - LOG.trace( - String.format( - "More than one representation of the same persistent entity being merged for: %s", - MessageHelper.infoString( - entityName, - session.getIdentifier( managedEntity ) - ) - ) - ); + if ( LOG.isTraceEnabled() ) { + LOG.trace( "More than one representation of the same persistent entity being merged for: " + + infoString( entityName, session.getIdentifier( managedEntity ) ) ); + } Set detachedEntitiesForManaged = null; if ( managedToMergeEntitiesXref == null ) { // This is the first time multiple representations have been found; @@ -125,7 +121,7 @@ public void topLevelMergeComplete(EventSource session) { } } else { - LOG.debug( "No entity copies merged." ); + LOG.debug( "No entity copies merged" ); } if ( managedToMergeEntitiesXref != null ) { @@ -135,12 +131,8 @@ public void topLevelMergeComplete(EventSource session) { final StringBuilder sb = new StringBuilder( "Details: merged ") .append( mergeEntities.size() ) .append( " representations of the same entity " ) - .append( - MessageHelper.infoString( - session.getEntityName( managedEntity ), - session.getIdentifier( managedEntity ) - ) - ) + .append( infoString( session.getEntityName( managedEntity ), + session.getIdentifier( managedEntity ) ) ) .append( " being merged: " ); boolean first = true; for ( Object mergeEntity : mergeEntities ) { diff --git a/hibernate-core/src/main/java/org/hibernate/event/internal/EvictVisitor.java b/hibernate-core/src/main/java/org/hibernate/event/internal/EvictVisitor.java index 912fa6641cb4..e76a8e2ad536 100644 --- a/hibernate-core/src/main/java/org/hibernate/event/internal/EvictVisitor.java +++ b/hibernate-core/src/main/java/org/hibernate/event/internal/EvictVisitor.java @@ -72,11 +72,8 @@ private void evictCollection(PersistentCollection collection) { final CollectionPersister persister = ce.getLoadedPersister(); final Object loadedKey = ce.getLoadedKey(); - if ( LOG.isDebugEnabled() ) { - LOG.debugf( - "Evicting collection: %s", - collectionInfoString( persister, collection, loadedKey, session ) - ); + if ( LOG.isTraceEnabled() ) { + LOG.trace( "Evicting collection: " + collectionInfoString( persister, collection, loadedKey, session ) ); } if ( persister != null ) { From af4342b62ce50746efc477d9160d6b38890d2d7e Mon Sep 17 00:00:00 2001 From: Gavin King Date: Mon, 14 Jul 2025 10:14:49 +0200 Subject: [PATCH 24/32] minor aesthetic cleanups in batch loader logging --- .../AbstractCollectionBatchLoader.java | 9 +++++---- .../internal/AbstractEntityBatchLoader.java | 7 +++++-- .../CollectionBatchLoaderArrayParam.java | 18 +++++++---------- .../CollectionBatchLoaderInPredicate.java | 20 +++++++++---------- .../internal/EntityBatchLoaderArrayParam.java | 8 +++++--- .../EntityBatchLoaderInPredicate.java | 17 ++++++++-------- .../MultiIdEntityLoaderInPredicate.java | 9 ++++----- 7 files changed, 44 insertions(+), 44 deletions(-) diff --git a/hibernate-core/src/main/java/org/hibernate/loader/ast/internal/AbstractCollectionBatchLoader.java b/hibernate-core/src/main/java/org/hibernate/loader/ast/internal/AbstractCollectionBatchLoader.java index 3e892ea7e800..31b43e538d47 100644 --- a/hibernate-core/src/main/java/org/hibernate/loader/ast/internal/AbstractCollectionBatchLoader.java +++ b/hibernate-core/src/main/java/org/hibernate/loader/ast/internal/AbstractCollectionBatchLoader.java @@ -24,6 +24,7 @@ import static org.hibernate.loader.ast.internal.MultiKeyLoadHelper.hasSingleId; import static org.hibernate.loader.ast.internal.MultiKeyLoadHelper.trimIdBatch; import static org.hibernate.loader.ast.internal.MultiKeyLoadLogging.MULTI_KEY_LOAD_LOGGER; +import static org.hibernate.pretty.MessageHelper.collectionInfoString; /** * @author Steve Ebersole @@ -80,8 +81,8 @@ public int getKeyJdbcCount() { @Override public PersistentCollection load(Object key, SharedSessionContractImplementor session) { if ( MULTI_KEY_LOAD_LOGGER.isTraceEnabled() ) { - MULTI_KEY_LOAD_LOGGER.tracef( "Batch fetching collection: %s.%s", - getLoadable().getNavigableRole().getFullPath(), key ); + MULTI_KEY_LOAD_LOGGER.trace( "Batch fetching collection: " + + collectionInfoString( getLoadable().getNavigableRole().getFullPath(), key ) ); } final Object[] keys = resolveKeysToInitialize( key, session ); @@ -106,8 +107,8 @@ protected void finishInitializingKey(Object key, SharedSessionContractImplemento } if ( MULTI_KEY_LOAD_LOGGER.isTraceEnabled() ) { - MULTI_KEY_LOAD_LOGGER.tracef( "Finishing initializing batch-fetched collection: %s.%s", - attributeMapping.getNavigableRole().getFullPath(), key ); + MULTI_KEY_LOAD_LOGGER.trace( "Finishing initializing batch-fetched collection: " + + collectionInfoString( attributeMapping.getNavigableRole().getFullPath(), key ) ); } final PersistenceContext persistenceContext = session.getPersistenceContext(); diff --git a/hibernate-core/src/main/java/org/hibernate/loader/ast/internal/AbstractEntityBatchLoader.java b/hibernate-core/src/main/java/org/hibernate/loader/ast/internal/AbstractEntityBatchLoader.java index 4a2eea7e0757..6d725fb59e9e 100644 --- a/hibernate-core/src/main/java/org/hibernate/loader/ast/internal/AbstractEntityBatchLoader.java +++ b/hibernate-core/src/main/java/org/hibernate/loader/ast/internal/AbstractEntityBatchLoader.java @@ -15,6 +15,7 @@ import static org.hibernate.loader.ast.internal.MultiKeyLoadHelper.hasSingleId; import static org.hibernate.loader.ast.internal.MultiKeyLoadLogging.MULTI_KEY_LOAD_LOGGER; +import static org.hibernate.pretty.MessageHelper.infoString; public abstract class AbstractEntityBatchLoader extends SingleIdEntityLoaderSupport @@ -45,7 +46,8 @@ public final T load( Boolean readOnly, SharedSessionContractImplementor session) { if ( MULTI_KEY_LOAD_LOGGER.isTraceEnabled() ) { - MULTI_KEY_LOAD_LOGGER.tracef( "Batch fetching entity `%s#%s`", getLoadable().getEntityName(), id ); + MULTI_KEY_LOAD_LOGGER.trace( "Batch fetching entity: " + + infoString( getLoadable().getEntityName(), id ) ); } final Object[] ids = resolveIdsToInitialize( id, session ); @@ -59,7 +61,8 @@ public T load( LockOptions lockOptions, SharedSessionContractImplementor session) { if ( MULTI_KEY_LOAD_LOGGER.isTraceEnabled() ) { - MULTI_KEY_LOAD_LOGGER.tracef( "Batch fetching entity `%s#%s`", getLoadable().getEntityName(), id ); + MULTI_KEY_LOAD_LOGGER.trace( "Batch fetching entity: " + + infoString( getLoadable().getEntityName(), id ) ); } final Object[] ids = resolveIdsToInitialize( id, session ); diff --git a/hibernate-core/src/main/java/org/hibernate/loader/ast/internal/CollectionBatchLoaderArrayParam.java b/hibernate-core/src/main/java/org/hibernate/loader/ast/internal/CollectionBatchLoaderArrayParam.java index 6fecce326b0a..52837da15b49 100644 --- a/hibernate-core/src/main/java/org/hibernate/loader/ast/internal/CollectionBatchLoaderArrayParam.java +++ b/hibernate-core/src/main/java/org/hibernate/loader/ast/internal/CollectionBatchLoaderArrayParam.java @@ -36,6 +36,7 @@ import static org.hibernate.loader.ast.internal.MultiKeyLoadHelper.hasSingleId; import static org.hibernate.loader.ast.internal.MultiKeyLoadHelper.trimIdBatch; import static org.hibernate.loader.ast.internal.MultiKeyLoadLogging.MULTI_KEY_LOAD_LOGGER; +import static org.hibernate.pretty.MessageHelper.collectionInfoString; /** * {@link CollectionBatchLoader} using a SQL {@code ARRAY} parameter to pass the key values. @@ -60,7 +61,7 @@ public CollectionBatchLoaderArrayParam( if ( MULTI_KEY_LOAD_LOGGER.isTraceEnabled() ) { MULTI_KEY_LOAD_LOGGER.tracef( - "Using ARRAY batch fetching strategy for collection `%s` : %s", + "Batch fetching enabled for collection '%s' using ARRAY strategy with batch size %s", attributeMapping.getNavigableRole().getFullPath(), domainBatchSize ); @@ -116,10 +117,8 @@ private PersistentCollection loadEmbeddable( SharedSessionContractImplementor session, ForeignKeyDescriptor keyDescriptor) { if ( MULTI_KEY_LOAD_LOGGER.isTraceEnabled() ) { - MULTI_KEY_LOAD_LOGGER.tracef( - "Batch fetching collection: %s.%s", - getLoadable().getNavigableRole().getFullPath(), keyBeingLoaded - ); + MULTI_KEY_LOAD_LOGGER.trace( "Batch fetching collection: " + + collectionInfoString( getLoadable().getNavigableRole().getFullPath(), keyBeingLoaded ) ); } final int length = getDomainBatchSize(); @@ -168,12 +167,9 @@ private PersistentCollection loadEmbeddable( @Override void initializeKeys(Object key, Object[] keysToInitialize, SharedSessionContractImplementor session) { if ( MULTI_KEY_LOAD_LOGGER.isTraceEnabled() ) { - MULTI_KEY_LOAD_LOGGER.tracef( - "Collection keys to batch-fetch initialize (`%s#%s`) %s", - getLoadable().getNavigableRole().getFullPath(), - key, - keysToInitialize - ); + MULTI_KEY_LOAD_LOGGER.tracef( "Collection keys to initialize via batch fetching (%s) %s", + collectionInfoString( getLoadable().getNavigableRole().getFullPath(), key ), + keysToInitialize ); } assert jdbcSelectOperation != null; diff --git a/hibernate-core/src/main/java/org/hibernate/loader/ast/internal/CollectionBatchLoaderInPredicate.java b/hibernate-core/src/main/java/org/hibernate/loader/ast/internal/CollectionBatchLoaderInPredicate.java index 00084429cfb1..5ec41113d939 100644 --- a/hibernate-core/src/main/java/org/hibernate/loader/ast/internal/CollectionBatchLoaderInPredicate.java +++ b/hibernate-core/src/main/java/org/hibernate/loader/ast/internal/CollectionBatchLoaderInPredicate.java @@ -23,6 +23,7 @@ import static org.hibernate.loader.ast.internal.MultiKeyLoadHelper.countIds; import static org.hibernate.loader.ast.internal.MultiKeyLoadLogging.MULTI_KEY_LOAD_LOGGER; +import static org.hibernate.pretty.MessageHelper.collectionInfoString; /** * {@link CollectionBatchLoader} for batch fetching using a SQL {@code IN} predicate. @@ -50,9 +51,9 @@ public CollectionBatchLoaderInPredicate( .getDialect() .getBatchLoadSizingStrategy() .determineOptimalBatchLoadSize( keyColumnCount, domainBatchSize, false ); - if ( MULTI_KEY_LOAD_LOGGER.isDebugEnabled() ) { + if ( MULTI_KEY_LOAD_LOGGER.isTraceEnabled() ) { MULTI_KEY_LOAD_LOGGER.tracef( - "Using IN-predicate batch fetching strategy for collection `%s` : %s (%s)", + "Batch fetching enabled for collection '%s' using IN-predicate with batch size %s (%s)", attributeMapping.getNavigableRole().getFullPath(), sqlBatchSize, domainBatchSize @@ -91,9 +92,8 @@ void initializeKeys(Object key, Object[] keysToInitialize, SharedSessionContract final boolean loggerDebugEnabled = MULTI_KEY_LOAD_LOGGER.isDebugEnabled(); if ( loggerDebugEnabled ) { MULTI_KEY_LOAD_LOGGER.tracef( - "Collection keys to batch-fetch initialize (`%s#%s`) %s", - getLoadable().getNavigableRole().getFullPath(), - key, + "Collection keys to initialize via batch fetching (%s) %s", + collectionInfoString( getLoadable().getNavigableRole().getFullPath(), key ), keysToInitialize ); } @@ -127,9 +127,8 @@ void initializeKeys(Object key, Object[] keysToInitialize, SharedSessionContract (startIndex) -> { if ( loggerDebugEnabled ) { MULTI_KEY_LOAD_LOGGER.tracef( - "Processing collection batch-fetch chunk (`%s#%s`) %s - %s", - getLoadable().getNavigableRole().getFullPath(), - key, + "Processing collection batch-fetch chunk (%s) %s - %s", + collectionInfoString( getLoadable().getNavigableRole().getFullPath(), key ), startIndex, startIndex + (sqlBatchSize-1) ); @@ -138,9 +137,8 @@ void initializeKeys(Object key, Object[] keysToInitialize, SharedSessionContract (startIndex, nonNullElementCount) -> { if ( loggerDebugEnabled ) { MULTI_KEY_LOAD_LOGGER.tracef( - "Finishing collection batch-fetch chunk (`%s#%s`) %s - %s (%s)", - getLoadable().getNavigableRole().getFullPath(), - key, + "Finishing collection batch-fetch chunk (%s) %s - %s (%s)", + collectionInfoString( getLoadable().getNavigableRole().getFullPath(), key ), startIndex, startIndex + (sqlBatchSize-1), nonNullElementCount diff --git a/hibernate-core/src/main/java/org/hibernate/loader/ast/internal/EntityBatchLoaderArrayParam.java b/hibernate-core/src/main/java/org/hibernate/loader/ast/internal/EntityBatchLoaderArrayParam.java index c03a4fdc1cdc..14ab770b9341 100644 --- a/hibernate-core/src/main/java/org/hibernate/loader/ast/internal/EntityBatchLoaderArrayParam.java +++ b/hibernate-core/src/main/java/org/hibernate/loader/ast/internal/EntityBatchLoaderArrayParam.java @@ -29,6 +29,7 @@ import static org.hibernate.loader.ast.internal.LoaderHelper.loadByArrayParameter; import static org.hibernate.loader.ast.internal.MultiKeyLoadHelper.trimIdBatch; import static org.hibernate.loader.ast.internal.MultiKeyLoadLogging.MULTI_KEY_LOAD_LOGGER; +import static org.hibernate.pretty.MessageHelper.infoString; /** * {@link SingleIdEntityLoaderSupport} implementation based on using a single @@ -69,7 +70,7 @@ public EntityBatchLoaderArrayParam( if ( MULTI_KEY_LOAD_LOGGER.isTraceEnabled() ) { MULTI_KEY_LOAD_LOGGER.tracef( - "Batch fetching enabled for `%s` (entity) using ARRAY strategy : %s", + "Batch fetching enabled for entity '%s' using ARRAY strategy with batch size %s", entityDescriptor.getEntityName(), domainBatchSize ); @@ -127,8 +128,9 @@ protected void initializeEntities( Boolean readOnly, SharedSessionContractImplementor session) { if ( MULTI_KEY_LOAD_LOGGER.isTraceEnabled() ) { - MULTI_KEY_LOAD_LOGGER.tracef( "Ids to batch-fetch initialize (`%s#%s`) %s", - getLoadable().getEntityName(), id, Arrays.toString(idsToInitialize) ); + MULTI_KEY_LOAD_LOGGER.tracef( "Entity ids to initialize via batch fetching (%s) %s", + infoString( getLoadable().getEntityName(), id), + Arrays.toString( idsToInitialize ) ); } removeBatchLoadableEntityKeys( idsToInitialize, session ); diff --git a/hibernate-core/src/main/java/org/hibernate/loader/ast/internal/EntityBatchLoaderInPredicate.java b/hibernate-core/src/main/java/org/hibernate/loader/ast/internal/EntityBatchLoaderInPredicate.java index 86c9c772a9ad..cc1d9c5d6191 100644 --- a/hibernate-core/src/main/java/org/hibernate/loader/ast/internal/EntityBatchLoaderInPredicate.java +++ b/hibernate-core/src/main/java/org/hibernate/loader/ast/internal/EntityBatchLoaderInPredicate.java @@ -24,6 +24,7 @@ import org.hibernate.sql.exec.spi.JdbcParametersList; import static org.hibernate.loader.ast.internal.MultiKeyLoadLogging.MULTI_KEY_LOAD_LOGGER; +import static org.hibernate.pretty.MessageHelper.infoString; /** * An {@link EntityBatchLoader} using one or more SQL queries, which each initialize up @@ -63,10 +64,10 @@ public EntityBatchLoaderInPredicate( if ( MULTI_KEY_LOAD_LOGGER.isTraceEnabled() ) { MULTI_KEY_LOAD_LOGGER.tracef( - "Batch fetching `%s` entity using padded IN-list: %s (%s)", + "Batch fetching enabled for entity '%s' using IN-predicate with batch size %s (%s)", entityDescriptor.getEntityName(), - domainBatchSize, - sqlBatchSize + sqlBatchSize, + domainBatchSize ); } @@ -122,8 +123,9 @@ protected void initializeEntities( Boolean readOnly, SharedSessionContractImplementor session) { if ( MULTI_KEY_LOAD_LOGGER.isTraceEnabled() ) { - MULTI_KEY_LOAD_LOGGER.tracef( "Ids to batch-fetch initialize (`%s#%s`) %s", - getLoadable().getEntityName(), pkValue, Arrays.toString(idsToInitialize) ); + MULTI_KEY_LOAD_LOGGER.tracef( "Entity ids to initialize via batch fetching (%s) %s", + infoString( getLoadable().getEntityName(), pkValue ), + Arrays.toString(idsToInitialize) ); } final BatchFetchQueue batchFetchQueue = session.getPersistenceContextInternal().getBatchFetchQueue(); @@ -158,9 +160,8 @@ protected void initializeEntities( (startIndex) -> { if ( MULTI_KEY_LOAD_LOGGER.isTraceEnabled() ) { MULTI_KEY_LOAD_LOGGER.tracef( - "Processing entity batch-fetch chunk (`%s#%s`) %s - %s", - getLoadable().getEntityName(), - pkValue, + "Processing entity batch-fetch chunk (%s) %s - %s", + infoString( getLoadable().getEntityName(), pkValue ), startIndex, startIndex + ( sqlBatchSize - 1 ) ); diff --git a/hibernate-core/src/main/java/org/hibernate/loader/ast/internal/MultiIdEntityLoaderInPredicate.java b/hibernate-core/src/main/java/org/hibernate/loader/ast/internal/MultiIdEntityLoaderInPredicate.java index 76d6fd167107..4bf0e4c074e1 100644 --- a/hibernate-core/src/main/java/org/hibernate/loader/ast/internal/MultiIdEntityLoaderInPredicate.java +++ b/hibernate-core/src/main/java/org/hibernate/loader/ast/internal/MultiIdEntityLoaderInPredicate.java @@ -29,7 +29,6 @@ import static java.util.Collections.singletonList; import static org.hibernate.engine.spi.SubselectFetch.createRegistrationHandler; import static org.hibernate.loader.ast.internal.LoaderSelectBuilder.createSelect; -import static org.hibernate.loader.ast.internal.MultiKeyLoadLogging.MULTI_KEY_LOAD_LOGGER; /** * Standard implementation of {@link org.hibernate.loader.ast.spi.MultiIdEntityLoader} @@ -96,10 +95,10 @@ private List performRegularMultiLoad( MultiIdLoadOptions loadOptions, SharedSessionContractImplementor session, int numberOfIdsInBatch) { - if ( MULTI_KEY_LOAD_LOGGER.isTraceEnabled() ) { - MULTI_KEY_LOAD_LOGGER.tracef( "#loadEntitiesById(`%s`, `%s`, ..)", - getLoadable().getEntityName(), numberOfIdsInBatch ); - } +// if ( MULTI_KEY_LOAD_LOGGER.isTraceEnabled() ) { +// MULTI_KEY_LOAD_LOGGER.tracef( "#loadEntitiesById(`%s`, `%s`, ..)", +// getLoadable().getEntityName(), numberOfIdsInBatch ); +// } final JdbcParametersList.Builder jdbcParametersBuilder = JdbcParametersList.newBuilder( numberOfIdsInBatch * idJdbcTypeCount ); From 363308a19216644f54de2496df7c6bc20a740db1 Mon Sep 17 00:00:00 2001 From: Gavin King Date: Mon, 14 Jul 2025 10:15:41 +0200 Subject: [PATCH 25/32] misc very minor consistency fixes for logging --- .../boot/jaxb/internal/XmlSources.java | 21 ++++++++-------- .../query/HbmResultSetMappingDescriptor.java | 24 +++++++++---------- .../jdbc/env/internal/LobCreationHelper.java | 4 ++-- 3 files changed, 25 insertions(+), 24 deletions(-) diff --git a/hibernate-core/src/main/java/org/hibernate/boot/jaxb/internal/XmlSources.java b/hibernate-core/src/main/java/org/hibernate/boot/jaxb/internal/XmlSources.java index 4790f71c39d7..fdc653f33fdd 100644 --- a/hibernate-core/src/main/java/org/hibernate/boot/jaxb/internal/XmlSources.java +++ b/hibernate-core/src/main/java/org/hibernate/boot/jaxb/internal/XmlSources.java @@ -16,7 +16,6 @@ import org.hibernate.boot.MappingNotFoundException; import org.hibernate.boot.archive.spi.InputStreamAccess; -import org.hibernate.boot.jaxb.JaxbLogger; import org.hibernate.boot.jaxb.Origin; import org.hibernate.boot.jaxb.SourceType; import org.hibernate.boot.jaxb.spi.XmlSource; @@ -24,6 +23,8 @@ import org.w3c.dom.Document; +import static org.hibernate.boot.jaxb.JaxbLogger.JAXB_LOGGER; + /** * Helper for building and handling {@link XmlSource} references. *

@@ -38,7 +39,7 @@ public class XmlSources { * Create an {@link XmlSource} from a named resource */ public static XmlSource fromResource(String resourceName, ClassLoaderService classLoaderService) { - JaxbLogger.JAXB_LOGGER.tracef( "reading mappings from resource : %s", resourceName ); + JAXB_LOGGER.tracef( "Reading mappings from resource: %s", resourceName ); final Origin origin = new Origin( SourceType.RESOURCE, resourceName ); final URL url = classLoaderService.locateResource( resourceName ); @@ -54,7 +55,7 @@ public static XmlSource fromResource(String resourceName, ClassLoaderService cla */ public static XmlSource fromUrl(URL url) { final String urlExternalForm = url.toExternalForm(); - JaxbLogger.JAXB_LOGGER.tracef( "Reading mapping document from URL : %s", urlExternalForm ); + JAXB_LOGGER.tracef( "Reading mapping document from URL: %s", urlExternalForm ); final Origin origin = new Origin( SourceType.URL, urlExternalForm ); return new UrlXmlSource( origin, url ); @@ -62,7 +63,7 @@ public static XmlSource fromUrl(URL url) { public static XmlSource fromFile(File file) { final String filePath = file.getPath(); - JaxbLogger.JAXB_LOGGER.tracef( "reading mappings from file : %s", filePath ); + JAXB_LOGGER.tracef( "Reading mappings from file: %s", filePath ); final Origin origin = new Origin( SourceType.FILE, filePath ); @@ -87,7 +88,7 @@ public static XmlSource fromCacheableFile(File file, boolean strict) { public static XmlSource fromCacheableFile(File file, File cacheableDir, boolean strict) { final String filePath = file.getPath(); - JaxbLogger.JAXB_LOGGER.tracef( "reading mappings from cacheable-file : %s", filePath ); + JAXB_LOGGER.tracef( "Reading mappings from cacheable file: %s", filePath ); final Origin origin = new Origin( SourceType.FILE, filePath ); return new CacheableFileXmlSource( origin, file, cacheableDir, strict ); @@ -95,21 +96,21 @@ public static XmlSource fromCacheableFile(File file, File cacheableDir, boolean public static XmlSource fromStream(InputStreamAccess inputStreamAccess) { final String streamName = inputStreamAccess.getStreamName(); - JaxbLogger.JAXB_LOGGER.tracef( "reading mappings from InputStreamAccess : %s", streamName ); + JAXB_LOGGER.tracef( "Reading mappings from InputStreamAccess: %s", streamName ); final Origin origin = new Origin( SourceType.INPUT_STREAM, streamName ); return new InputStreamAccessXmlSource( origin, inputStreamAccess ); } public static XmlSource fromStream(InputStream inputStream) { - JaxbLogger.JAXB_LOGGER.trace( "reading mappings from InputStream" ); + JAXB_LOGGER.trace( "reading mappings from InputStream" ); final Origin origin = new Origin( SourceType.INPUT_STREAM, null ); return new InputStreamXmlSource( origin, inputStream, false ); } public static XmlSource fromDocument(Document document) { - JaxbLogger.JAXB_LOGGER.trace( "reading mappings from DOM" ); + JAXB_LOGGER.trace( "reading mappings from DOM" ); final Origin origin = new Origin( SourceType.DOM, Origin.UNKNOWN_FILE_PATH ); return new JaxpSourceXmlSource( origin, new DOMSource( document ) ); } @@ -125,7 +126,7 @@ public static XmlSource fromDocument(Document document) { * @param consumer a consumer of the resulting {@linkplain XmlSource XML sources} */ public static void fromJar(File jar, Consumer consumer) { - JaxbLogger.JAXB_LOGGER.tracef( "Seeking mapping documents in jar file : %s", jar.getName() ); + JAXB_LOGGER.tracef( "Seeking mapping documents in jar file: %s", jar.getName() ); final Origin origin = new Origin( SourceType.JAR, jar.getAbsolutePath() ); @@ -134,7 +135,7 @@ public static void fromJar(File jar, Consumer consumer) { while ( entries.hasMoreElements() ) { final JarEntry jarEntry = entries.nextElement(); if ( jarEntry.getName().endsWith(".hbm.xml") ) { - JaxbLogger.JAXB_LOGGER.tracef( "Found hbm.xml mapping in jar : %s", jarEntry.getName() ); + JAXB_LOGGER.tracef( "Found 'hbm.xml' mapping in jar: %s", jarEntry.getName() ); consumer.accept( new JarFileEntryXmlSource( origin, jarFile, jarEntry ) ); } } diff --git a/hibernate-core/src/main/java/org/hibernate/boot/query/HbmResultSetMappingDescriptor.java b/hibernate-core/src/main/java/org/hibernate/boot/query/HbmResultSetMappingDescriptor.java index f89921cb4ac3..6906e0f398b4 100644 --- a/hibernate-core/src/main/java/org/hibernate/boot/query/HbmResultSetMappingDescriptor.java +++ b/hibernate-core/src/main/java/org/hibernate/boot/query/HbmResultSetMappingDescriptor.java @@ -105,7 +105,7 @@ public HbmResultSetMappingDescriptor( if ( hbmValueMapping == null ) { throw new IllegalStateException( - "ValueMappingSources contained null reference(s)" + "ValueMappingSources contained null reference" ); } @@ -138,7 +138,7 @@ else if ( hbmValueMapping instanceof JaxbHbmNativeQueryScalarReturnType hbmScala } else { throw new IllegalArgumentException( - "Unknown NativeQueryReturn type : " + hbmValueMapping.getClass().getName() + "Unknown NativeQueryReturn type: " + hbmValueMapping.getClass().getName() ); } } @@ -158,13 +158,13 @@ public static void collectJoinFetch( Map fetchParentByAlias, String registrationName, MetadataBuildingContext context) { - // property path is in the form `{ownerAlias}.{joinedPath}`. Split it into the 2 parts + // property path is in the form {ownerAlias}.{joinedPath}. Split it into the 2 parts. final String fullPropertyPath = jaxbHbmJoin.getProperty(); final int firstDot = fullPropertyPath.indexOf( '.' ); if ( firstDot < 1 ) { throw new MappingException( - "Illegal property attribute: `" + fullPropertyPath + "`. Should" - + "be in the form `{ownerAlias.joinedPropertyPath}` (" + registrationName + ")" + "Illegal property attribute: '" + fullPropertyPath + "' - " + + " - should be in the form '{ownerAlias.joinedPropertyPath}' (" + registrationName + ")" ); } @@ -182,8 +182,8 @@ public static void collectJoinFetch( final JoinDescriptor existing = joinDescriptorsForAlias.get( propertyPath ); if ( existing != null ) { throw new MappingException( - "Property join specified twice for join-return `" + ownerTableAlias + "." + propertyPath - + "` (" + registrationName + ")" + "Property join specified twice for join-return '" + ownerTableAlias + "." + propertyPath + + "' (" + registrationName + ")" ); } @@ -200,8 +200,8 @@ public static void collectJoinFetch( /** - * Constructor for an implicit resultset mapping defined inline as part of a `<sql-query/>` - * stanza + * Constructor for an implicit resultset mapping defined inline + * as part of a '<sql-query/>' stanza. */ public HbmResultSetMappingDescriptor( String registrationName, @@ -269,7 +269,7 @@ public NamedResultSetMappingMemento resolve(ResultSetMappingResolutionContext re // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - // `hbm.xml` returns + // hbm.xml returns public interface HbmFetchDescriptor extends FetchDescriptor { String getFetchablePath(); @@ -722,8 +722,8 @@ public JoinDescriptor( final int firstDot = fullPropertyPath.indexOf( '.' ); if ( firstDot < 1 ) { throw new MappingException( - "Illegal property attribute: `" + fullPropertyPath + "`. Should" - + "be in the form `{ownerAlias.joinedPropertyPath}`" + "Illegal property attribute: '" + fullPropertyPath + "'" + + " - should be in the form '{ownerAlias.joinedPropertyPath}'" ); } diff --git a/hibernate-core/src/main/java/org/hibernate/engine/jdbc/env/internal/LobCreationHelper.java b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/env/internal/LobCreationHelper.java index 7693d6979a6a..2ede0b53f9bc 100644 --- a/hibernate-core/src/main/java/org/hibernate/engine/jdbc/env/internal/LobCreationHelper.java +++ b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/env/internal/LobCreationHelper.java @@ -86,7 +86,7 @@ private static boolean canCreateClob(Connection jdbcConnection) { clob.free(); } catch (Throwable e) { - LOB_LOGGER.tracef( "Unable to free CLOB created to test createClob() implementation : %s", e ); + LOB_LOGGER.tracef( "Unable to free CLOB created to test createClob() implementation: %s", e ); } return true; } @@ -104,7 +104,7 @@ private static boolean canCreateNClob(Connection jdbcConnection) { clob.free(); } catch (Throwable e) { - LOB_LOGGER.tracef( "Unable to free NCLOB created to test createNClob() implementation : %s", e ); + LOB_LOGGER.tracef( "Unable to free NCLOB created to test createNClob() implementation: %s", e ); } return true; } From 41fcfa032194810cab0257fc4e4843579f764c71 Mon Sep 17 00:00:00 2001 From: Gavin King Date: Mon, 14 Jul 2025 10:16:17 +0200 Subject: [PATCH 26/32] migrate QueryResultsCacheImpl logging to SecondLevelCacheLogger --- .../cache/internal/QueryResultsCacheImpl.java | 19 ++++----- .../cache/spi/SecondLevelCacheLogger.java | 39 ++++++++++++++++++- 2 files changed, 47 insertions(+), 11 deletions(-) diff --git a/hibernate-core/src/main/java/org/hibernate/cache/internal/QueryResultsCacheImpl.java b/hibernate-core/src/main/java/org/hibernate/cache/internal/QueryResultsCacheImpl.java index 02a437fa8f4b..9cdfa54d6fa4 100644 --- a/hibernate-core/src/main/java/org/hibernate/cache/internal/QueryResultsCacheImpl.java +++ b/hibernate-core/src/main/java/org/hibernate/cache/internal/QueryResultsCacheImpl.java @@ -51,7 +51,7 @@ public boolean put( final List results, final SharedSessionContractImplementor session) throws HibernateException { if ( L2CACHE_LOGGER.isTraceEnabled() ) { - L2CACHE_LOGGER.tracef( "Caching query results in region: %s; timestamp=%s", + L2CACHE_LOGGER.cachingQueryResults( cacheRegion.getName(), session.getCacheTransactionSynchronization().getCachingTimestamp() ); } @@ -92,26 +92,26 @@ public List get( final SharedSessionContractImplementor session) throws HibernateException { final boolean loggerTraceEnabled = L2CACHE_LOGGER.isTraceEnabled(); if ( loggerTraceEnabled ) { - L2CACHE_LOGGER.tracef( "Checking cached query results in region: %s", cacheRegion.getName() ); + L2CACHE_LOGGER.checkingCachedQueryResults( cacheRegion.getName() ); } final CacheItem cacheItem = getCachedData( key, session ); if ( cacheItem == null ) { if ( loggerTraceEnabled ) { - L2CACHE_LOGGER.trace( "Query results were not found in cache" ); + L2CACHE_LOGGER.queryResultsNotFound(); } return null; } if ( !timestampsCache.isUpToDate( spaces, cacheItem.timestamp, session ) ) { if ( loggerTraceEnabled ) { - L2CACHE_LOGGER.trace( "Cached query results were not up-to-date" ); + L2CACHE_LOGGER.cachedQueryResultsStale(); } return null; } if ( loggerTraceEnabled ) { - L2CACHE_LOGGER.trace( "Returning cached query results" ); + L2CACHE_LOGGER.returningCachedQueryResults(); } // No need to copy results, since consumers will never mutate @@ -124,27 +124,28 @@ public List get( final String[] spaces, final SharedSessionContractImplementor session) throws HibernateException { final boolean loggerTraceEnabled = L2CACHE_LOGGER.isTraceEnabled(); + if ( loggerTraceEnabled ) { - L2CACHE_LOGGER.tracef( "Checking cached query results in region: %s", cacheRegion.getName() ); + L2CACHE_LOGGER.checkingCachedQueryResults( cacheRegion.getName() ); } final CacheItem cacheItem = getCachedData( key, session ); if ( cacheItem == null ) { if ( loggerTraceEnabled ) { - L2CACHE_LOGGER.trace( "Query results were not found in cache" ); + L2CACHE_LOGGER.queryResultsNotFound(); } return null; } if ( !timestampsCache.isUpToDate( spaces, cacheItem.timestamp, session ) ) { if ( loggerTraceEnabled ) { - L2CACHE_LOGGER.trace( "Cached query results were not up-to-date" ); + L2CACHE_LOGGER.cachedQueryResultsStale(); } return null; } if ( loggerTraceEnabled ) { - L2CACHE_LOGGER.trace( "Returning cached query results" ); + L2CACHE_LOGGER.returningCachedQueryResults(); } return deepCopy( cacheItem.results ); diff --git a/hibernate-core/src/main/java/org/hibernate/cache/spi/SecondLevelCacheLogger.java b/hibernate-core/src/main/java/org/hibernate/cache/spi/SecondLevelCacheLogger.java index 98b5e548a96c..ae9bb69bef8e 100644 --- a/hibernate-core/src/main/java/org/hibernate/cache/spi/SecondLevelCacheLogger.java +++ b/hibernate-core/src/main/java/org/hibernate/cache/spi/SecondLevelCacheLogger.java @@ -17,6 +17,7 @@ import java.lang.invoke.MethodHandles; import static org.jboss.logging.Logger.Level.INFO; +import static org.jboss.logging.Logger.Level.TRACE; import static org.jboss.logging.Logger.Level.WARN; /** @@ -26,7 +27,7 @@ @ValidIdRange( min = 90001001, max = 90002000 ) @SubSystemLogging( name = SecondLevelCacheLogger.LOGGER_NAME, - description = "Logging related to Hibernate second-level caching" + description = "Logging related to the second-level cache" ) @Internal public interface SecondLevelCacheLogger extends BasicLogger { @@ -60,7 +61,7 @@ public interface SecondLevelCacheLogger extends BasicLogger { @LogMessage( level = WARN ) @Message( - value = "Read-only caching was requested for mutable natural-id for entity [%s]", + value = "Read-only caching was requested for entity [%s] with mutable natural id", id = NAMESPACE + 4 ) void readOnlyCachingMutableNaturalId(String entity); @@ -100,4 +101,38 @@ public interface SecondLevelCacheLogger extends BasicLogger { @SuppressWarnings( "unused" ) // used by hibernate-jcache void nonStandardSupportForAccessType(String regionName, String accessType, String regionFactoryClass); + @LogMessage(level = TRACE) + @Message( + value = "Caching query results in region '%s' with timestamp %s", + id = NAMESPACE + 9 + ) + void cachingQueryResults(String regionName, long timestamp); + + @LogMessage(level = TRACE) + @Message( + value = "Checking cached query results in region '%s'", + id = NAMESPACE + 10 + ) + void checkingCachedQueryResults(String regionName); + + @LogMessage(level = TRACE) + @Message( + value = "Query results were not found in cache", + id = NAMESPACE + 11 + ) + void queryResultsNotFound(); + + @LogMessage(level = TRACE) + @Message( + value = "Cached query results were stale", + id = NAMESPACE + 12 + ) + void cachedQueryResultsStale(); + + @LogMessage(level = TRACE) + @Message( + value = "Returning cached query results", + id = NAMESPACE + 14 + ) + void returningCachedQueryResults(); } From c041ec47121a80ce029bdfcb40890ede6dc2b637 Mon Sep 17 00:00:00 2001 From: Gavin King Date: Mon, 14 Jul 2025 11:12:04 +0200 Subject: [PATCH 27/32] introduce new infoString methods for batch loaders --- .../ast/internal/AbstractCollectionBatchLoader.java | 4 ++-- .../ast/internal/AbstractEntityBatchLoader.java | 4 ++-- .../ast/internal/AbstractMultiIdEntityLoader.java | 4 ++-- .../ast/internal/AbstractMultiNaturalIdLoader.java | 2 +- .../internal/CollectionBatchLoaderArrayParam.java | 12 ++++++------ .../internal/CollectionBatchLoaderInPredicate.java | 6 +++--- .../ast/internal/DatabaseSnapshotExecutor.java | 9 +++++---- .../ast/internal/EntityBatchLoaderArrayParam.java | 2 +- .../ast/internal/EntityBatchLoaderInPredicate.java | 4 ++-- .../hibernate/loader/ast/internal/LoaderHelper.java | 2 +- .../java/org/hibernate/pretty/MessageHelper.java | 11 +++++++++++ 11 files changed, 36 insertions(+), 24 deletions(-) diff --git a/hibernate-core/src/main/java/org/hibernate/loader/ast/internal/AbstractCollectionBatchLoader.java b/hibernate-core/src/main/java/org/hibernate/loader/ast/internal/AbstractCollectionBatchLoader.java index 31b43e538d47..3d146b129a4e 100644 --- a/hibernate-core/src/main/java/org/hibernate/loader/ast/internal/AbstractCollectionBatchLoader.java +++ b/hibernate-core/src/main/java/org/hibernate/loader/ast/internal/AbstractCollectionBatchLoader.java @@ -82,7 +82,7 @@ public int getKeyJdbcCount() { public PersistentCollection load(Object key, SharedSessionContractImplementor session) { if ( MULTI_KEY_LOAD_LOGGER.isTraceEnabled() ) { MULTI_KEY_LOAD_LOGGER.trace( "Batch fetching collection: " - + collectionInfoString( getLoadable().getNavigableRole().getFullPath(), key ) ); + + collectionInfoString( getLoadable(), key ) ); } final Object[] keys = resolveKeysToInitialize( key, session ); @@ -108,7 +108,7 @@ protected void finishInitializingKey(Object key, SharedSessionContractImplemento if ( MULTI_KEY_LOAD_LOGGER.isTraceEnabled() ) { MULTI_KEY_LOAD_LOGGER.trace( "Finishing initializing batch-fetched collection: " - + collectionInfoString( attributeMapping.getNavigableRole().getFullPath(), key ) ); + + collectionInfoString( attributeMapping, key ) ); } final PersistenceContext persistenceContext = session.getPersistenceContext(); diff --git a/hibernate-core/src/main/java/org/hibernate/loader/ast/internal/AbstractEntityBatchLoader.java b/hibernate-core/src/main/java/org/hibernate/loader/ast/internal/AbstractEntityBatchLoader.java index 6d725fb59e9e..456042d2998f 100644 --- a/hibernate-core/src/main/java/org/hibernate/loader/ast/internal/AbstractEntityBatchLoader.java +++ b/hibernate-core/src/main/java/org/hibernate/loader/ast/internal/AbstractEntityBatchLoader.java @@ -47,7 +47,7 @@ public final T load( SharedSessionContractImplementor session) { if ( MULTI_KEY_LOAD_LOGGER.isTraceEnabled() ) { MULTI_KEY_LOAD_LOGGER.trace( "Batch fetching entity: " - + infoString( getLoadable().getEntityName(), id ) ); + + infoString( getLoadable(), id ) ); } final Object[] ids = resolveIdsToInitialize( id, session ); @@ -62,7 +62,7 @@ public T load( SharedSessionContractImplementor session) { if ( MULTI_KEY_LOAD_LOGGER.isTraceEnabled() ) { MULTI_KEY_LOAD_LOGGER.trace( "Batch fetching entity: " - + infoString( getLoadable().getEntityName(), id ) ); + + infoString( getLoadable(), id ) ); } final Object[] ids = resolveIdsToInitialize( id, session ); diff --git a/hibernate-core/src/main/java/org/hibernate/loader/ast/internal/AbstractMultiIdEntityLoader.java b/hibernate-core/src/main/java/org/hibernate/loader/ast/internal/AbstractMultiIdEntityLoader.java index 9073f15f310b..a5a6344d5d34 100644 --- a/hibernate-core/src/main/java/org/hibernate/loader/ast/internal/AbstractMultiIdEntityLoader.java +++ b/hibernate-core/src/main/java/org/hibernate/loader/ast/internal/AbstractMultiIdEntityLoader.java @@ -92,7 +92,7 @@ private List performUnorderedMultiLoad( assert !loadOptions.isOrderReturnEnabled(); assert ids != null; if ( MULTI_KEY_LOAD_LOGGER.isTraceEnabled() ) { - MULTI_KEY_LOAD_LOGGER.tracef( "Unordered MultiLoad starting: " + MULTI_KEY_LOAD_LOGGER.tracef( "Unordered batch load starting: " + getLoadable().getEntityName() ); } return unorderedMultiLoad( ids, loadOptions, session ); @@ -105,7 +105,7 @@ private List performOrderedMultiLoad( assert loadOptions.isOrderReturnEnabled(); assert ids != null; if ( MULTI_KEY_LOAD_LOGGER.isTraceEnabled() ) { - MULTI_KEY_LOAD_LOGGER.tracef( "Ordered MultiLoad starting: " + MULTI_KEY_LOAD_LOGGER.tracef( "Ordered batch load starting: " + getLoadable().getEntityName() ); } return orderedMultiLoad( ids, loadOptions, session ); diff --git a/hibernate-core/src/main/java/org/hibernate/loader/ast/internal/AbstractMultiNaturalIdLoader.java b/hibernate-core/src/main/java/org/hibernate/loader/ast/internal/AbstractMultiNaturalIdLoader.java index 014c4086efed..b443696922e4 100644 --- a/hibernate-core/src/main/java/org/hibernate/loader/ast/internal/AbstractMultiNaturalIdLoader.java +++ b/hibernate-core/src/main/java/org/hibernate/loader/ast/internal/AbstractMultiNaturalIdLoader.java @@ -52,7 +52,7 @@ private List performUnorderedMultiLoad( MultiNaturalIdLoadOptions loadOptions, SharedSessionContractImplementor session) { if ( MULTI_KEY_LOAD_LOGGER.isTraceEnabled() ) { - MULTI_KEY_LOAD_LOGGER.tracef( "Unordered MultiLoad starting: " + MULTI_KEY_LOAD_LOGGER.tracef( "Unordered batch load starting: " + getEntityDescriptor().getEntityName() ); } return unorderedMultiLoad( naturalIds, loadOptions, session ); diff --git a/hibernate-core/src/main/java/org/hibernate/loader/ast/internal/CollectionBatchLoaderArrayParam.java b/hibernate-core/src/main/java/org/hibernate/loader/ast/internal/CollectionBatchLoaderArrayParam.java index 52837da15b49..e2865830fac0 100644 --- a/hibernate-core/src/main/java/org/hibernate/loader/ast/internal/CollectionBatchLoaderArrayParam.java +++ b/hibernate-core/src/main/java/org/hibernate/loader/ast/internal/CollectionBatchLoaderArrayParam.java @@ -4,7 +4,6 @@ */ package org.hibernate.loader.ast.internal; -import java.lang.reflect.Array; import org.hibernate.LockOptions; import org.hibernate.collection.spi.PersistentCollection; @@ -33,6 +32,7 @@ import org.hibernate.sql.results.internal.RowTransformerStandardImpl; import org.hibernate.sql.results.spi.ListResultsConsumer; +import static java.lang.reflect.Array.newInstance; import static org.hibernate.loader.ast.internal.MultiKeyLoadHelper.hasSingleId; import static org.hibernate.loader.ast.internal.MultiKeyLoadHelper.trimIdBatch; import static org.hibernate.loader.ast.internal.MultiKeyLoadLogging.MULTI_KEY_LOAD_LOGGER; @@ -118,11 +118,11 @@ private PersistentCollection loadEmbeddable( ForeignKeyDescriptor keyDescriptor) { if ( MULTI_KEY_LOAD_LOGGER.isTraceEnabled() ) { MULTI_KEY_LOAD_LOGGER.trace( "Batch fetching collection: " - + collectionInfoString( getLoadable().getNavigableRole().getFullPath(), keyBeingLoaded ) ); + + collectionInfoString( getLoadable(), keyBeingLoaded ) ); } final int length = getDomainBatchSize(); - final Object[] keysToInitialize = (Object[]) Array.newInstance( + final Object[] keysToInitialize = (Object[]) newInstance( jdbcParameter.getExpressionType() .getSingleJdbcMapping() .getJdbcJavaType() @@ -130,7 +130,7 @@ private PersistentCollection loadEmbeddable( .getComponentType(), length ); - final Object[] embeddedKeys = (Object[]) Array.newInstance( keyDomainType, length ); + final Object[] embeddedKeys = (Object[]) newInstance( keyDomainType, length ); session.getPersistenceContextInternal().getBatchFetchQueue() .collectBatchLoadableCollectionKeys( length, @@ -168,7 +168,7 @@ private PersistentCollection loadEmbeddable( void initializeKeys(Object key, Object[] keysToInitialize, SharedSessionContractImplementor session) { if ( MULTI_KEY_LOAD_LOGGER.isTraceEnabled() ) { MULTI_KEY_LOAD_LOGGER.tracef( "Collection keys to initialize via batch fetching (%s) %s", - collectionInfoString( getLoadable().getNavigableRole().getFullPath(), key ), + collectionInfoString( getLoadable(), key ), keysToInitialize ); } @@ -214,7 +214,7 @@ Object[] resolveKeysToInitialize(Object keyBeingLoaded, SharedSessionContractImp if( keyDescriptor.isEmbedded()){ assert keyDescriptor.getJdbcTypeCount() == 1; final int length = getDomainBatchSize(); - final Object[] keysToInitialize = (Object[]) Array.newInstance( keyDescriptor.getSingleJdbcMapping().getJdbcJavaType().getJavaTypeClass(), length ); + final Object[] keysToInitialize = (Object[]) newInstance( keyDescriptor.getSingleJdbcMapping().getJdbcJavaType().getJavaTypeClass(), length ); session.getPersistenceContextInternal().getBatchFetchQueue() .collectBatchLoadableCollectionKeys( length, diff --git a/hibernate-core/src/main/java/org/hibernate/loader/ast/internal/CollectionBatchLoaderInPredicate.java b/hibernate-core/src/main/java/org/hibernate/loader/ast/internal/CollectionBatchLoaderInPredicate.java index 5ec41113d939..9e4127bb7f1e 100644 --- a/hibernate-core/src/main/java/org/hibernate/loader/ast/internal/CollectionBatchLoaderInPredicate.java +++ b/hibernate-core/src/main/java/org/hibernate/loader/ast/internal/CollectionBatchLoaderInPredicate.java @@ -93,7 +93,7 @@ void initializeKeys(Object key, Object[] keysToInitialize, SharedSessionContract if ( loggerDebugEnabled ) { MULTI_KEY_LOAD_LOGGER.tracef( "Collection keys to initialize via batch fetching (%s) %s", - collectionInfoString( getLoadable().getNavigableRole().getFullPath(), key ), + collectionInfoString( getLoadable(), key ), keysToInitialize ); } @@ -128,7 +128,7 @@ void initializeKeys(Object key, Object[] keysToInitialize, SharedSessionContract if ( loggerDebugEnabled ) { MULTI_KEY_LOAD_LOGGER.tracef( "Processing collection batch-fetch chunk (%s) %s - %s", - collectionInfoString( getLoadable().getNavigableRole().getFullPath(), key ), + collectionInfoString( getLoadable(), key ), startIndex, startIndex + (sqlBatchSize-1) ); @@ -138,7 +138,7 @@ void initializeKeys(Object key, Object[] keysToInitialize, SharedSessionContract if ( loggerDebugEnabled ) { MULTI_KEY_LOAD_LOGGER.tracef( "Finishing collection batch-fetch chunk (%s) %s - %s (%s)", - collectionInfoString( getLoadable().getNavigableRole().getFullPath(), key ), + collectionInfoString( getLoadable(), key ), startIndex, startIndex + (sqlBatchSize-1), nonNullElementCount diff --git a/hibernate-core/src/main/java/org/hibernate/loader/ast/internal/DatabaseSnapshotExecutor.java b/hibernate-core/src/main/java/org/hibernate/loader/ast/internal/DatabaseSnapshotExecutor.java index 26b8d73b1a5e..2a944aa10b3d 100644 --- a/hibernate-core/src/main/java/org/hibernate/loader/ast/internal/DatabaseSnapshotExecutor.java +++ b/hibernate-core/src/main/java/org/hibernate/loader/ast/internal/DatabaseSnapshotExecutor.java @@ -43,13 +43,13 @@ import org.hibernate.type.BasicType; import org.hibernate.type.StandardBasicTypes; -import org.jboss.logging.Logger; +import static org.hibernate.loader.LoaderLogging.LOADER_LOGGER; +import static org.hibernate.pretty.MessageHelper.infoString; /** * @author Steve Ebersole */ class DatabaseSnapshotExecutor { - private static final Logger log = Logger.getLogger( DatabaseSnapshotExecutor.class ); private final EntityMappingType entityDescriptor; @@ -154,8 +154,9 @@ class DatabaseSnapshotExecutor { } Object[] loadDatabaseSnapshot(Object id, SharedSessionContractImplementor session) { - if ( log.isTraceEnabled() ) { - log.tracef( "Getting current persistent state for `%s#%s`", entityDescriptor.getEntityName(), id ); + if ( LOADER_LOGGER.isTraceEnabled() ) { + LOADER_LOGGER.trace( "Retrieving snapshot of current persistent state for " + + infoString( entityDescriptor, id ) ); } final JdbcParameterBindings jdbcParameterBindings = new JdbcParameterBindingsImpl( diff --git a/hibernate-core/src/main/java/org/hibernate/loader/ast/internal/EntityBatchLoaderArrayParam.java b/hibernate-core/src/main/java/org/hibernate/loader/ast/internal/EntityBatchLoaderArrayParam.java index 14ab770b9341..d48523f0c125 100644 --- a/hibernate-core/src/main/java/org/hibernate/loader/ast/internal/EntityBatchLoaderArrayParam.java +++ b/hibernate-core/src/main/java/org/hibernate/loader/ast/internal/EntityBatchLoaderArrayParam.java @@ -129,7 +129,7 @@ protected void initializeEntities( SharedSessionContractImplementor session) { if ( MULTI_KEY_LOAD_LOGGER.isTraceEnabled() ) { MULTI_KEY_LOAD_LOGGER.tracef( "Entity ids to initialize via batch fetching (%s) %s", - infoString( getLoadable().getEntityName(), id), + infoString( getLoadable(), id), Arrays.toString( idsToInitialize ) ); } diff --git a/hibernate-core/src/main/java/org/hibernate/loader/ast/internal/EntityBatchLoaderInPredicate.java b/hibernate-core/src/main/java/org/hibernate/loader/ast/internal/EntityBatchLoaderInPredicate.java index cc1d9c5d6191..27015477396e 100644 --- a/hibernate-core/src/main/java/org/hibernate/loader/ast/internal/EntityBatchLoaderInPredicate.java +++ b/hibernate-core/src/main/java/org/hibernate/loader/ast/internal/EntityBatchLoaderInPredicate.java @@ -124,7 +124,7 @@ protected void initializeEntities( SharedSessionContractImplementor session) { if ( MULTI_KEY_LOAD_LOGGER.isTraceEnabled() ) { MULTI_KEY_LOAD_LOGGER.tracef( "Entity ids to initialize via batch fetching (%s) %s", - infoString( getLoadable().getEntityName(), pkValue ), + infoString( getLoadable(), pkValue ), Arrays.toString(idsToInitialize) ); } @@ -161,7 +161,7 @@ protected void initializeEntities( if ( MULTI_KEY_LOAD_LOGGER.isTraceEnabled() ) { MULTI_KEY_LOAD_LOGGER.tracef( "Processing entity batch-fetch chunk (%s) %s - %s", - infoString( getLoadable().getEntityName(), pkValue ), + infoString( getLoadable(), pkValue ), startIndex, startIndex + ( sqlBatchSize - 1 ) ); diff --git a/hibernate-core/src/main/java/org/hibernate/loader/ast/internal/LoaderHelper.java b/hibernate-core/src/main/java/org/hibernate/loader/ast/internal/LoaderHelper.java index 6aad19c69c4f..bac6c670fdc5 100644 --- a/hibernate-core/src/main/java/org/hibernate/loader/ast/internal/LoaderHelper.java +++ b/hibernate-core/src/main/java/org/hibernate/loader/ast/internal/LoaderHelper.java @@ -100,7 +100,7 @@ public static void upgradeLock( else { throw new IllegalStateException( String.format( "Trying to lock versioned entity %s but found null version", - infoString( persister.getEntityName(), entry.getId() ) + infoString( persister, entry.getId() ) ) ); } } diff --git a/hibernate-core/src/main/java/org/hibernate/pretty/MessageHelper.java b/hibernate-core/src/main/java/org/hibernate/pretty/MessageHelper.java index aff4b6ae2bd8..3e5254e34efa 100644 --- a/hibernate-core/src/main/java/org/hibernate/pretty/MessageHelper.java +++ b/hibernate-core/src/main/java/org/hibernate/pretty/MessageHelper.java @@ -9,6 +9,8 @@ import org.hibernate.engine.spi.EntityEntry; import org.hibernate.engine.spi.SessionFactoryImplementor; import org.hibernate.engine.spi.SharedSessionContractImplementor; +import org.hibernate.metamodel.mapping.EntityMappingType; +import org.hibernate.metamodel.mapping.PluralAttributeMapping; import org.hibernate.persister.collection.CollectionPersister; import org.hibernate.persister.entity.EntityPersister; import org.hibernate.type.Type; @@ -387,4 +389,13 @@ public static String collectionInfoString(@Nullable String role, @Nullable Objec return info.toString(); } + public static String collectionInfoString(PluralAttributeMapping loadable, Object key) { + final CollectionPersister collectionDescriptor = loadable.getCollectionDescriptor(); + return collectionInfoString( collectionDescriptor, key, collectionDescriptor.getFactory() ); + } + + public static String infoString(EntityMappingType loadable, Object id) { + final EntityPersister persister = loadable.getEntityPersister(); + return infoString( persister, id, persister.getFactory() ); + } } From 4404d9cf80b628c892b9bbbd7188a44eb915e20a Mon Sep 17 00:00:00 2001 From: Gavin King Date: Mon, 14 Jul 2025 11:38:33 +0200 Subject: [PATCH 28/32] fix jdoc of QueryResultsCacheImpl --- .../org/hibernate/cache/internal/QueryResultsCacheImpl.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/hibernate-core/src/main/java/org/hibernate/cache/internal/QueryResultsCacheImpl.java b/hibernate-core/src/main/java/org/hibernate/cache/internal/QueryResultsCacheImpl.java index 9cdfa54d6fa4..3f9f8b1f1b0f 100644 --- a/hibernate-core/src/main/java/org/hibernate/cache/internal/QueryResultsCacheImpl.java +++ b/hibernate-core/src/main/java/org/hibernate/cache/internal/QueryResultsCacheImpl.java @@ -21,8 +21,8 @@ import static org.hibernate.cache.spi.SecondLevelCacheLogger.L2CACHE_LOGGER; /** - * The standard implementation of the Hibernate QueryCache interface. Works - * hind-in-hand with {@link TimestampsCache} to help in recognizing + * The standard implementation of the {@link QueryResultsCache} interface. + * Works in conjunction with {@link TimestampsCache} to help in recognizing * stale query results. * * @author Gavin King From 1c8dcc2668d1a1aaa665514da63026176b36a7d5 Mon Sep 17 00:00:00 2001 From: Gavin King Date: Mon, 14 Jul 2025 12:05:55 +0200 Subject: [PATCH 29/32] use typesafe logging for all L2 cache stuff --- .../internal/CollectionCacheInvalidator.java | 11 ++- .../cache/internal/EnabledCaching.java | 35 ++------ .../internal/TimestampsCacheEnabledImpl.java | 42 ++++----- .../cache/spi/SecondLevelCacheLogger.java | 90 ++++++++++++++++++- 4 files changed, 121 insertions(+), 57 deletions(-) diff --git a/hibernate-core/src/main/java/org/hibernate/cache/internal/CollectionCacheInvalidator.java b/hibernate-core/src/main/java/org/hibernate/cache/internal/CollectionCacheInvalidator.java index 7f2c5155d270..5d7fad4695e5 100644 --- a/hibernate-core/src/main/java/org/hibernate/cache/internal/CollectionCacheInvalidator.java +++ b/hibernate-core/src/main/java/org/hibernate/cache/internal/CollectionCacheInvalidator.java @@ -32,8 +32,10 @@ import org.jboss.logging.Logger; +import static org.hibernate.cache.spi.SecondLevelCacheLogger.L2CACHE_LOGGER; import static org.hibernate.internal.util.StringHelper.isEmpty; import static org.hibernate.internal.util.collections.CollectionHelper.isEmpty; +import static org.hibernate.pretty.MessageHelper.collectionInfoString; /** * Allows the collection cache to be automatically evicted if an element is inserted/removed/updated *without* properly @@ -127,8 +129,8 @@ private void evictCollection( handleInverseOneToMany( entity, persister, oldState, collectionPersister, session ); } else { - if ( LOG.isTraceEnabled() ) { - LOG.trace( "Evict CollectionRegion " + collectionPersister.getRole() ); + if ( L2CACHE_LOGGER.isTraceEnabled() ) { + L2CACHE_LOGGER.autoEvictingCollectionCacheByRole( collectionPersister.getRole() ); } final CollectionDataAccess cacheAccessStrategy = collectionPersister.getCacheAccessStrategy(); final SoftLock softLock = cacheAccessStrategy.lockRegion(); @@ -184,8 +186,9 @@ private Object getIdentifier(SharedSessionContractImplementor session, Object ob } private void evict(Object id, CollectionPersister collectionPersister, EventSource session) { - if ( LOG.isTraceEnabled() ) { - LOG.trace( "Evict CollectionRegion " + collectionPersister.getRole() + " for id " + id ); + if ( L2CACHE_LOGGER.isTraceEnabled() ) { + L2CACHE_LOGGER.autoEvictingCollectionCache( + collectionInfoString( collectionPersister, id, collectionPersister.getFactory() ) ); } final CollectionEvictCacheAction evictCacheAction = new CollectionEvictCacheAction( collectionPersister, null, id, session ); diff --git a/hibernate-core/src/main/java/org/hibernate/cache/internal/EnabledCaching.java b/hibernate-core/src/main/java/org/hibernate/cache/internal/EnabledCaching.java index da7c98f010a8..3ad8e89b0eb4 100644 --- a/hibernate-core/src/main/java/org/hibernate/cache/internal/EnabledCaching.java +++ b/hibernate-core/src/main/java/org/hibernate/cache/internal/EnabledCaching.java @@ -34,12 +34,11 @@ import org.hibernate.cache.spi.access.EntityDataAccess; import org.hibernate.cache.spi.access.NaturalIdDataAccess; import org.hibernate.engine.spi.SessionFactoryImplementor; -import org.hibernate.internal.CoreLogging; -import org.hibernate.internal.CoreMessageLogger; import org.hibernate.metamodel.model.domain.NavigableRole; import org.hibernate.metamodel.spi.MappingMetamodelImplementor; import org.hibernate.persister.collection.CollectionPersister; import org.hibernate.persister.entity.EntityPersister; +import org.hibernate.cache.spi.SecondLevelCacheLogger; import static org.hibernate.internal.util.StringHelper.qualifyConditionally; import static org.hibernate.pretty.MessageHelper.collectionInfoString; @@ -53,7 +52,7 @@ * @author Gail Badner */ public class EnabledCaching implements CacheImplementor, DomainDataRegionBuildingContext { - private static final CoreMessageLogger LOG = CoreLogging.messageLogger( EnabledCaching.class ); + private static final SecondLevelCacheLogger LOG = SecondLevelCacheLogger.L2CACHE_LOGGER; private final SessionFactoryImplementor sessionFactory; private final RegionFactory regionFactory; @@ -259,10 +258,7 @@ public void evictEntityData(String entityName, Object identifier) { final EntityPersister persister = getEntityDescriptor( entityName ); final EntityDataAccess cacheAccess = persister.getCacheAccessStrategy(); if ( cacheAccess != null ) { - if ( LOG.isTraceEnabled() ) { - LOG.trace( "Evicting entity second-level cache: " - + infoString( persister, identifier, sessionFactory ) ); - } + LOG.evictingEntityCache( infoString( persister, identifier, sessionFactory ) ); final Object cacheKey = cacheAccess.generateCacheKey( identifier, persister, sessionFactory, null ); @@ -305,9 +301,7 @@ protected void evictEntityData(EntityPersister entityDescriptor) { private void evictEntityData(NavigableRole navigableRole, EntityDataAccess cacheAccess) { if ( cacheAccess != null ) { - if ( LOG.isTraceEnabled() ) { - LOG.trace( "Evicting entity second-level cache: " + navigableRole.getFullPath() ); - } + LOG.evictingEntityCacheByRole( navigableRole.getFullPath() ); cacheAccess.evictAll(); } } @@ -344,9 +338,7 @@ public void evictNaturalIdData() { private void evictNaturalIdData(NavigableRole rootEntityRole, NaturalIdDataAccess cacheAccess) { if ( cacheAccess != null ) { - if ( LOG.isTraceEnabled() ) { - LOG.trace( "Evicting natural-id cache: " + rootEntityRole.getFullPath() ); - } + LOG.evictingNaturalIdCache( rootEntityRole.getFullPath() ); cacheAccess.evictAll(); } } @@ -375,10 +367,7 @@ public void evictCollectionData(String role, Object ownerIdentifier) { final CollectionPersister persister = getCollectionDescriptor( role ); final CollectionDataAccess cacheAccess = persister.getCacheAccessStrategy(); if ( cacheAccess != null ) { - if ( LOG.isTraceEnabled() ) { - LOG.trace( "Evicting collection second-level cache: " - + collectionInfoString( persister, ownerIdentifier, sessionFactory ) ); - } + LOG.evictingCollectionCache( collectionInfoString( persister, ownerIdentifier, sessionFactory ) ); final Object cacheKey = cacheAccess.generateCacheKey( ownerIdentifier, persister, sessionFactory, null ); @@ -398,9 +387,7 @@ private void evictCollectionData(CollectionPersister collectionDescriptor) { private void evictCollectionData(NavigableRole navigableRole, CollectionDataAccess cacheAccess) { if ( cacheAccess != null ) { - if ( LOG.isTraceEnabled() ) { - LOG.trace( "Evicting collection second-level cache: " + navigableRole.getFullPath() ); - } + LOG.evictingCollectionCacheByRole( navigableRole.getFullPath() ); cacheAccess.evictAll(); } } @@ -435,18 +422,14 @@ public void evictQueryRegion(String regionName) { private void evictQueryResultRegion(QueryResultsCache cache) { if ( cache != null ) { - if ( LOG.isTraceEnabled() ) { - LOG.trace( "Evicting query cache region: " + cache.getRegion().getName() ); - } + LOG.evictingQueryCacheRegion( cache.getRegion().getName() ); cache.clear(); } } @Override public void evictQueryRegions() { - if ( LOG.isTraceEnabled() ) { - LOG.trace( "Evicting cache of all query regions" ); - } + LOG.evictingAllQueryRegions(); evictQueryResultRegion( defaultQueryResultsCache ); for ( QueryResultsCache cache : namedQueryResultsCacheMap.values() ) { diff --git a/hibernate-core/src/main/java/org/hibernate/cache/internal/TimestampsCacheEnabledImpl.java b/hibernate-core/src/main/java/org/hibernate/cache/internal/TimestampsCacheEnabledImpl.java index 362d93c30f68..2021f1a26f6a 100644 --- a/hibernate-core/src/main/java/org/hibernate/cache/internal/TimestampsCacheEnabledImpl.java +++ b/hibernate-core/src/main/java/org/hibernate/cache/internal/TimestampsCacheEnabledImpl.java @@ -16,7 +16,9 @@ import org.hibernate.event.monitor.spi.DiagnosticEvent; import org.hibernate.stat.spi.StatisticsImplementor; -import org.jboss.logging.Logger; +import static org.hibernate.cache.spi.SecondLevelCacheLogger.L2CACHE_LOGGER; +import static org.hibernate.event.monitor.spi.EventMonitor.CacheActionDescription.TIMESTAMP_INVALIDATE; +import static org.hibernate.event.monitor.spi.EventMonitor.CacheActionDescription.TIMESTAMP_PRE_INVALIDATE; /** * Standard implementation of TimestampsCache @@ -24,9 +26,6 @@ * @author Steve Ebersole */ public class TimestampsCacheEnabledImpl implements TimestampsCache { - private static final Logger log = Logger.getLogger( TimestampsCacheEnabledImpl.class ); - - public static final boolean TRACE_ENABLED = log.isTraceEnabled(); private final TimestampsRegion timestampsRegion; @@ -45,20 +44,18 @@ public void preInvalidate( SharedSessionContractImplementor session) { final SessionFactoryImplementor factory = session.getFactory(); final RegionFactory regionFactory = factory.getCache().getRegionFactory(); - final StatisticsImplementor statistics = factory.getStatistics(); final boolean stats = statistics.isStatisticsEnabled(); final Long timestamp = regionFactory.nextTimestamp() + regionFactory.getTimeout(); final SessionEventListenerManager eventListenerManager = session.getEventListenerManager(); - final boolean traceEnabled = log.isTraceEnabled(); - + final EventMonitor eventMonitor = session.getEventMonitor(); + final boolean traceEnabled = L2CACHE_LOGGER.isTraceEnabled(); for ( String space : spaces ) { if ( traceEnabled ) { - log.tracef( "Pre-invalidating space [%s], timestamp: %s", space, timestamp ); + L2CACHE_LOGGER.preInvalidatingSpace( space, timestamp ); } - final EventMonitor eventMonitor = session.getEventMonitor(); final DiagnosticEvent cachePutEvent = eventMonitor.beginCachePutEvent(); try { eventListenerManager.cachePutStart(); @@ -73,7 +70,7 @@ public void preInvalidate( session, timestampsRegion, true, - EventMonitor.CacheActionDescription.TIMESTAMP_PRE_INVALIDATE + TIMESTAMP_PRE_INVALIDATE ); eventListenerManager.cachePutEnd(); } @@ -88,23 +85,24 @@ public void preInvalidate( public void invalidate( String[] spaces, SharedSessionContractImplementor session) { - final StatisticsImplementor statistics = session.getFactory().getStatistics(); + final SessionFactoryImplementor factory = session.getFactory(); + final StatisticsImplementor statistics = factory.getStatistics(); final boolean stats = statistics.isStatisticsEnabled(); - final Long ts = session.getFactory().getCache().getRegionFactory().nextTimestamp(); - final boolean traceEnabled = log.isTraceEnabled(); + final Long timestamp = factory.getCache().getRegionFactory().nextTimestamp(); + final SessionEventListenerManager eventListenerManager = session.getEventListenerManager(); + final EventMonitor eventMonitor = session.getEventMonitor(); + final boolean traceEnabled = L2CACHE_LOGGER.isTraceEnabled(); for ( String space : spaces ) { if ( traceEnabled ) { - log.tracef( "Invalidating space [%s], timestamp: %s", space, ts ); + L2CACHE_LOGGER.invalidatingSpace( space, timestamp ); } - final SessionEventListenerManager eventListenerManager = session.getEventListenerManager(); - final EventMonitor eventMonitor = session.getEventMonitor(); final DiagnosticEvent cachePutEvent = eventMonitor.beginCachePutEvent(); try { eventListenerManager.cachePutStart(); - timestampsRegion.putIntoCache( space, ts, session ); + timestampsRegion.putIntoCache( space, timestamp, session ); } finally { eventMonitor.completeCachePutEvent( @@ -112,7 +110,7 @@ public void invalidate( session, timestampsRegion, true, - EventMonitor.CacheActionDescription.TIMESTAMP_INVALIDATE + TIMESTAMP_INVALIDATE ); eventListenerManager.cachePutEnd(); @@ -152,13 +150,7 @@ private boolean isSpaceOutOfDate( return false; } else { - if ( TRACE_ENABLED ) { - log.tracef( - "[%s] last update timestamp: %s", - space, - lastUpdate + ", result set timestamp: " + timestamp - ); - } + L2CACHE_LOGGER.lastUpdateTimestampForSpace( space, lastUpdate, timestamp ); if ( statistics.isStatisticsEnabled() ) { statistics.updateTimestampsCacheHit(); } diff --git a/hibernate-core/src/main/java/org/hibernate/cache/spi/SecondLevelCacheLogger.java b/hibernate-core/src/main/java/org/hibernate/cache/spi/SecondLevelCacheLogger.java index ae9bb69bef8e..236a707e5051 100644 --- a/hibernate-core/src/main/java/org/hibernate/cache/spi/SecondLevelCacheLogger.java +++ b/hibernate-core/src/main/java/org/hibernate/cache/spi/SecondLevelCacheLogger.java @@ -131,8 +131,94 @@ public interface SecondLevelCacheLogger extends BasicLogger { @LogMessage(level = TRACE) @Message( - value = "Returning cached query results", - id = NAMESPACE + 14 + value = "Returning cached query results", + id = NAMESPACE + 14 ) void returningCachedQueryResults(); + + @LogMessage(level = TRACE) + @Message( + value = "Evicting entity second-level cache: %s", + id = NAMESPACE + 15 + ) + void evictingEntityCache(String entityInfo); + + @LogMessage(level = TRACE) + @Message( + value = "Evicting entity second-level cache: %s", + id = NAMESPACE + 16 + ) + void evictingEntityCacheByRole(String role); + + @LogMessage(level = TRACE) + @Message( + value = "Evicting natural id cache: %s", + id = NAMESPACE + 17 + ) + void evictingNaturalIdCache(String role); + + @LogMessage(level = TRACE) + @Message( + value = "Evicting collection second-level cache: %s", + id = NAMESPACE + 18 + ) + void evictingCollectionCache(String collectionInfo); + + @LogMessage(level = TRACE) + @Message( + value = "Evicting collection second-level cache: %s", + id = NAMESPACE + 19 + ) + void evictingCollectionCacheByRole(String role); + + @LogMessage(level = TRACE) + @Message( + value = "Auto-evicting collection from second-level cache: %s" + + " (since 'hibernate.cache.auto_evict_collection_cache' is enabled)", + id = NAMESPACE + 25 + ) + void autoEvictingCollectionCache(String collectionInfo); + + @LogMessage(level = TRACE) + @Message( + value = "Auto-evicting collection from second-level cache: %s" + + " (since 'hibernate.cache.auto_evict_collection_cache' is enabled)", + id = NAMESPACE + 26 + ) + void autoEvictingCollectionCacheByRole(String collectionRole); + + @LogMessage(level = TRACE) + @Message( + value = "Evicting query cache region: %s", + id = NAMESPACE + 20 + ) + void evictingQueryCacheRegion(String regionName); + + @LogMessage(level = TRACE) + @Message( + value = "Evicting cache of all query regions", + id = NAMESPACE + 21 + ) + void evictingAllQueryRegions(); + + @LogMessage(level = TRACE) + @Message( + value = "Pre-invalidating space [%s], timestamp: %s", + id = NAMESPACE + 22 + ) + void preInvalidatingSpace(String space, Long timestamp); + + @LogMessage(level = TRACE) + @Message( + value = "Invalidating space [%s], timestamp: %s", + id = NAMESPACE + 23 + ) + void invalidatingSpace(String space, Long timestamp); + + @LogMessage(level = TRACE) + @Message( + value = "[%s] last update timestamp: %s, result set timestamp: %s", + id = NAMESPACE + 24 + ) + void lastUpdateTimestampForSpace(String space, Long lastUpdate, Long timestamp); } From 7d892c5773a2f374d070fc7bc96ea505aa042878 Mon Sep 17 00:00:00 2001 From: Gavin King Date: Mon, 14 Jul 2025 12:51:21 +0200 Subject: [PATCH 30/32] Use L2CACHE_LOGGER from o.h.cache.spi.support --- .../AbstractCachedDomainDataAccess.java | 6 +- .../spi/support/AbstractDomainDataRegion.java | 13 ++-- .../spi/support/AbstractReadWriteAccess.java | 66 ++++++++++--------- .../spi/support/DomainDataRegionTemplate.java | 39 +++++------ .../spi/support/EntityReadOnlyAccess.java | 4 +- 5 files changed, 62 insertions(+), 66 deletions(-) diff --git a/hibernate-core/src/main/java/org/hibernate/cache/spi/support/AbstractCachedDomainDataAccess.java b/hibernate-core/src/main/java/org/hibernate/cache/spi/support/AbstractCachedDomainDataAccess.java index e19b27278577..20326a78f66d 100644 --- a/hibernate-core/src/main/java/org/hibernate/cache/spi/support/AbstractCachedDomainDataAccess.java +++ b/hibernate-core/src/main/java/org/hibernate/cache/spi/support/AbstractCachedDomainDataAccess.java @@ -10,13 +10,13 @@ import org.hibernate.cache.spi.access.SoftLock; import org.hibernate.engine.spi.SharedSessionContractImplementor; -import org.jboss.logging.Logger; + +import static org.hibernate.cache.spi.SecondLevelCacheLogger.L2CACHE_LOGGER; /** * @author Steve Ebersole */ public abstract class AbstractCachedDomainDataAccess implements CachedDomainDataAccess, AbstractDomainDataRegion.Destructible { - private static final Logger log = Logger.getLogger( AbstractCachedDomainDataAccess.class ); private final DomainDataRegion region; private final DomainDataStorageAccess storageAccess; @@ -39,7 +39,7 @@ public DomainDataStorageAccess getStorageAccess() { } protected void clearCache() { - log.tracef( "Clearing cache data map [region=`%s`]", region.getName() ); + L2CACHE_LOGGER.tracef( "Clearing cache data map [region='%s']", region.getName() ); getStorageAccess().evictData(); } diff --git a/hibernate-core/src/main/java/org/hibernate/cache/spi/support/AbstractDomainDataRegion.java b/hibernate-core/src/main/java/org/hibernate/cache/spi/support/AbstractDomainDataRegion.java index 7ca32e503a15..4ddddbc05ce0 100644 --- a/hibernate-core/src/main/java/org/hibernate/cache/spi/support/AbstractDomainDataRegion.java +++ b/hibernate-core/src/main/java/org/hibernate/cache/spi/support/AbstractDomainDataRegion.java @@ -25,13 +25,13 @@ import org.hibernate.internal.util.collections.CollectionHelper; import org.hibernate.metamodel.model.domain.NavigableRole; -import org.jboss.logging.Logger; + +import static org.hibernate.cache.spi.SecondLevelCacheLogger.L2CACHE_LOGGER; /** * @author Steve Ebersole */ public abstract class AbstractDomainDataRegion extends AbstractRegion implements DomainDataRegion { - private static final Logger log = Logger.getLogger( AbstractDomainDataRegion.class ); private final SessionFactoryImplementor sessionFactory; private final CacheKeysFactory effectiveKeysFactory; @@ -67,7 +67,8 @@ public AbstractDomainDataRegion( protected void completeInstantiation( DomainDataRegionConfig regionConfig, DomainDataRegionBuildingContext buildingContext) { - log.tracef( "DomainDataRegion created [%s]; key-factory = %s", regionConfig.getRegionName(), effectiveKeysFactory ); + L2CACHE_LOGGER.tracef( "DomainDataRegion created [%s]; key-factory = %s", + regionConfig.getRegionName(), effectiveKeysFactory ); this.entityDataAccessMap = generateEntityDataAccessMap( regionConfig ); this.naturalIdDataAccessMap = generateNaturalIdDataAccessMap( regionConfig ); @@ -87,7 +88,7 @@ public CacheKeysFactory getEffectiveKeysFactory() { public EntityDataAccess getEntityDataAccess(NavigableRole rootEntityRole) { final EntityDataAccess access = entityDataAccessMap.get( rootEntityRole ); if ( access == null ) { - throw new IllegalArgumentException( "Caching was not configured for entity : " + rootEntityRole.getFullPath() ); + throw new IllegalArgumentException( "Caching was not configured for entity: " + rootEntityRole.getFullPath() ); } return access; } @@ -97,7 +98,7 @@ public EntityDataAccess getEntityDataAccess(NavigableRole rootEntityRole) { public NaturalIdDataAccess getNaturalIdDataAccess(NavigableRole rootEntityRole) { final NaturalIdDataAccess access = naturalIdDataAccessMap.get( rootEntityRole ); if ( access == null ) { - throw new IllegalArgumentException( "Caching was not configured for entity natural-id : " + rootEntityRole.getFullPath() ); + throw new IllegalArgumentException( "Caching was not configured for entity natural id: " + rootEntityRole.getFullPath() ); } return access; } @@ -106,7 +107,7 @@ public NaturalIdDataAccess getNaturalIdDataAccess(NavigableRole rootEntityRole) public CollectionDataAccess getCollectionDataAccess(NavigableRole collectionRole) { final CollectionDataAccess access = collectionDataAccessMap.get( collectionRole ); if ( access == null ) { - throw new IllegalArgumentException( "Caching was not configured for collection : " + collectionRole.getFullPath() ); + throw new IllegalArgumentException( "Caching was not configured for collection: " + collectionRole.getFullPath() ); } return access; } diff --git a/hibernate-core/src/main/java/org/hibernate/cache/spi/support/AbstractReadWriteAccess.java b/hibernate-core/src/main/java/org/hibernate/cache/spi/support/AbstractReadWriteAccess.java index bb30d0ed308d..65f31ec56c78 100644 --- a/hibernate-core/src/main/java/org/hibernate/cache/spi/support/AbstractReadWriteAccess.java +++ b/hibernate-core/src/main/java/org/hibernate/cache/spi/support/AbstractReadWriteAccess.java @@ -17,7 +17,6 @@ import org.hibernate.cache.spi.access.SoftLock; import org.hibernate.engine.spi.SharedSessionContractImplementor; -import org.jboss.logging.Logger; import static org.hibernate.cache.spi.SecondLevelCacheLogger.L2CACHE_LOGGER; @@ -25,7 +24,6 @@ * @author Steve Ebersole */ public abstract class AbstractReadWriteAccess extends AbstractCachedDomainDataAccess { - private static final Logger log = Logger.getLogger( AbstractReadWriteAccess.class ); private final UUID uuid = UUID.randomUUID(); private final AtomicLong nextLockId = new AtomicLong(); @@ -63,9 +61,10 @@ protected Lock writeLock() { */ @Override public Object get(SharedSessionContractImplementor session, Object key) { - final boolean traceEnabled = log.isTraceEnabled(); + final boolean traceEnabled = L2CACHE_LOGGER.isTraceEnabled(); if ( traceEnabled ) { - log.tracef( "Getting cached data from region [`%s` (%s)] by key [%s]", getRegion().getName(), getAccessType(), key ); + L2CACHE_LOGGER.tracef( "Getting cached data from region ['%s' (%s)] by key [%s]", + getRegion().getName(), getAccessType(), key ); } try { readLock.lock(); @@ -73,7 +72,8 @@ public Object get(SharedSessionContractImplementor session, Object key) { if ( item == null ) { if ( traceEnabled ) { - log.tracef( "Cache miss : region = `%s`, key = `%s`", getRegion().getName(), key ); + L2CACHE_LOGGER.tracef( "Cache miss: region = '%s', key = '%s'", + getRegion().getName(), key ); } return null; } @@ -81,13 +81,15 @@ public Object get(SharedSessionContractImplementor session, Object key) { final boolean readable = item.isReadable( session.getCacheTransactionSynchronization().getCachingTimestamp() ); if ( readable ) { if ( traceEnabled ) { - log.tracef( "Cache hit : region = `%s`, key = `%s`", getRegion().getName(), key ); + L2CACHE_LOGGER.tracef( "Cache hit: region = '%s', key = '%s'", + getRegion().getName(), key ); } return item.getValue(); } else { if ( traceEnabled ) { - log.tracef( "Cache hit, but item is unreadable/invalid : region = `%s`, key = `%s`", getRegion().getName(), key ); + L2CACHE_LOGGER.tracef( "Cache hit, but item is unreadable/invalid: region = '%s', key = '%s'", + getRegion().getName(), key ); } return null; } @@ -104,9 +106,10 @@ public boolean putFromLoad( Object value, Object version) { try { - final boolean traceEnabled = log.isTraceEnabled(); + final boolean traceEnabled = L2CACHE_LOGGER.isTraceEnabled(); if ( traceEnabled ) { - log.tracef( "Caching data from load [region='%s' (%s)] : key[%s] -> value[%s]", getRegion().getName(), getAccessType(), key, value ); + L2CACHE_LOGGER.tracef( "Caching data from load [region='%s' (%s)] : key[%s] -> value[%s]", + getRegion().getName(), getAccessType(), key, value ); } writeLock.lock(); Lockable item = (Lockable) getStorageAccess().getFromCache( key, session ); @@ -122,8 +125,8 @@ public boolean putFromLoad( } else { if ( traceEnabled ) { - log.tracef( - "Cache put-from-load [region=`%s` (%s), key=`%s`, value=`%s`] failed due to being non-writable", + L2CACHE_LOGGER.tracef( + "Cache put-from-load [region='%s' (%s), key='%s', value='%s'] failed due to being non-writable", getAccessType(), getRegion().getName(), key, @@ -156,8 +159,9 @@ public SoftLock lockItem(SharedSessionContractImplementor session, Object key, O writeLock.lock(); long timeout = getRegion().getRegionFactory().nextTimestamp() + getRegion().getRegionFactory().getTimeout(); - if ( log.isTraceEnabled() ) { - log.tracef( "Locking cache item [region=`%s` (%s)] : `%s` (timeout=%s, version=%s)", getRegion().getName(), getAccessType(), key, timeout, version ); + if ( L2CACHE_LOGGER.isTraceEnabled() ) { + L2CACHE_LOGGER.tracef( "Locking cache item [region='%s' (%s)] : '%s' (timeout=%s, version=%s)", + getRegion().getName(), getAccessType(), key, timeout, version ); } Lockable item = (Lockable) getStorageAccess().getFromCache( key, session ); @@ -175,18 +179,14 @@ public SoftLock lockItem(SharedSessionContractImplementor session, Object key, O @Override public void unlockItem(SharedSessionContractImplementor session, Object key, SoftLock lock) { try { - if ( log.isTraceEnabled() ) { - log.tracef( - "Unlocking cache item [region=`%s` (%s)] : %s", - getRegion().getName(), - getAccessType(), - key - ); + if ( L2CACHE_LOGGER.isTraceEnabled() ) { + L2CACHE_LOGGER.tracef( "Unlocking cache item [region='%s' (%s)] : %s", + getRegion().getName(), getAccessType(), key ); } writeLock.lock(); Lockable item = (Lockable) getStorageAccess().getFromCache( key, session ); - if ( ( item != null ) && item.isUnlockable( lock ) ) { + if ( item != null && item.isUnlockable( lock ) ) { decrementLock( session, key, (SoftLockImpl) item ); } else { @@ -205,7 +205,7 @@ protected void decrementLock(SharedSessionContractImplementor session, Object ke protected void handleLockExpiry(SharedSessionContractImplementor session, Object key, Lockable lock) { L2CACHE_LOGGER.softLockedCacheExpired( getRegion().getName(), key ); - log.tracef( "Cached entry expired: %s", key ); + L2CACHE_LOGGER.tracef( "Cached entry expired: %s", key ); final RegionFactory regionFactory = getRegion().getRegionFactory(); // create new lock that times out immediately @@ -219,7 +219,9 @@ protected void handleLockExpiry(SharedSessionContractImplementor session, Object @Override public void remove(SharedSessionContractImplementor session, Object key) { if ( getStorageAccess().getFromCache( key, session ) instanceof SoftLock ) { - log.debugf( "Skipping #remove call in read-write access to maintain SoftLock: %s", key ); + if ( L2CACHE_LOGGER.isDebugEnabled() ) { + L2CACHE_LOGGER.debugf( "Skipping remove call in read-write access to maintain SoftLock: ", key ); + } // don't do anything... we want the SoftLock to remain in place } else { @@ -285,9 +287,9 @@ public final static class Item implements Serializable, Lockable { @Override public boolean isReadable(long txTimestamp) { - if ( log.isTraceEnabled() ) { - log.tracef( - "Checking readability of read-write cache item [timestamp=`%s`, version=`%s`] : txTimestamp=`%s`", + if ( L2CACHE_LOGGER.isTraceEnabled() ) { + L2CACHE_LOGGER.tracef( + "Checking readability of read-write cache item [timestamp='%s', version='%s'] : txTimestamp='%s'", (Object) timestamp, version, txTimestamp @@ -299,9 +301,9 @@ public boolean isReadable(long txTimestamp) { @Override public boolean isWriteable(long txTimestamp, Object newVersion, Comparator versionComparator) { - if ( log.isTraceEnabled() ) { - log.tracef( - "Checking writeability of read-write cache item [timestamp=`%s`, version=`%s`] : txTimestamp=`%s`, newVersion=`%s`", + if ( L2CACHE_LOGGER.isTraceEnabled() ) { + L2CACHE_LOGGER.tracef( + "Checking writeability of read-write cache item [timestamp='%s', version='%s'] : txTimestamp='%s', newVersion='%s'", timestamp, version, txTimestamp, @@ -372,9 +374,9 @@ public boolean isReadable(long txTimestamp) { @Override public boolean isWriteable(long txTimestamp, Object newVersion, Comparator versionComparator) { - if ( log.isTraceEnabled() ) { - log.tracef( - "Checking writeability of read-write cache lock [timeout=`%s`, lockId=`%s`, version=`%s`, sourceUuid=%s, multiplicity=`%s`, unlockTimestamp=`%s`] : txTimestamp=`%s`, newVersion=`%s`", + if ( L2CACHE_LOGGER.isTraceEnabled() ) { + L2CACHE_LOGGER.tracef( + "Checking writeability of read-write cache lock [timeout='%s', lockId='%s', version='%s', sourceUuid=%s, multiplicity='%s', unlockTimestamp='%s'] : txTimestamp='%s', newVersion='%s'", timeout, lockId, version, diff --git a/hibernate-core/src/main/java/org/hibernate/cache/spi/support/DomainDataRegionTemplate.java b/hibernate-core/src/main/java/org/hibernate/cache/spi/support/DomainDataRegionTemplate.java index 8afacfcf56bd..9d77619e9e06 100644 --- a/hibernate-core/src/main/java/org/hibernate/cache/spi/support/DomainDataRegionTemplate.java +++ b/hibernate-core/src/main/java/org/hibernate/cache/spi/support/DomainDataRegionTemplate.java @@ -17,7 +17,8 @@ import org.hibernate.cache.spi.access.NaturalIdDataAccess; import org.hibernate.metamodel.model.domain.NavigableRole; -import org.jboss.logging.Logger; + +import static org.hibernate.cache.spi.SecondLevelCacheLogger.L2CACHE_LOGGER; /** * Abstract implementation of {@link org.hibernate.cache.spi.DomainDataRegion} based @@ -37,7 +38,6 @@ * @author Steve Ebersole */ public class DomainDataRegionTemplate extends AbstractDomainDataRegion { - private static final Logger log = Logger.getLogger( DomainDataRegionTemplate.class ); private final DomainDataStorageAccess storageAccess; @@ -67,25 +67,15 @@ public EntityDataAccess generateEntityAccess(EntityDataCachingConfig entityAcces final NavigableRole namedEntityRole = entityAccessConfig.getNavigableRole(); final AccessType accessType = entityAccessConfig.getAccessType(); - log.tracef( "Generating entity cache access [%s] : %s", accessType.getExternalName(), namedEntityRole ); - - switch ( accessType ) { - case READ_ONLY: { - return generateReadOnlyEntityAccess( entityAccessConfig ); - } - case READ_WRITE: { - return generateReadWriteEntityAccess( entityAccessConfig ); - } - case NONSTRICT_READ_WRITE: { - return generateNonStrictReadWriteEntityAccess( entityAccessConfig ); - } - case TRANSACTIONAL: { - return generateTransactionalEntityDataAccess( entityAccessConfig ); - } - default: { - throw new IllegalArgumentException( "Unrecognized cache AccessType - " + accessType ); - } - } + L2CACHE_LOGGER.tracef( "Generating entity cache access [%s] : %s", + accessType.getExternalName(), namedEntityRole ); + + return switch ( accessType ) { + case READ_ONLY -> generateReadOnlyEntityAccess( entityAccessConfig ); + case READ_WRITE -> generateReadWriteEntityAccess( entityAccessConfig ); + case NONSTRICT_READ_WRITE -> generateNonStrictReadWriteEntityAccess( entityAccessConfig ); + case TRANSACTIONAL -> generateTransactionalEntityDataAccess( entityAccessConfig ); + }; } protected EntityDataAccess generateReadOnlyEntityAccess(EntityDataCachingConfig accessConfig) { @@ -128,7 +118,8 @@ public NaturalIdDataAccess generateNaturalIdAccess(NaturalIdDataCachingConfig ac final NavigableRole namedEntityRole = accessConfig.getNavigableRole(); final AccessType accessType = accessConfig.getAccessType(); - log.tracef( "Generating entity natural-id access [%s] : %s", accessType.getExternalName(), namedEntityRole ); + L2CACHE_LOGGER.tracef( "Generating entity natural-id access [%s] : %s", + accessType.getExternalName(), namedEntityRole ); return switch ( accessType ) { case READ_ONLY -> generateReadOnlyNaturalIdAccess( accessConfig ); @@ -173,7 +164,9 @@ protected NaturalIdDataAccess generateTransactionalNaturalIdDataAccess(NaturalId public CollectionDataAccess generateCollectionAccess(CollectionDataCachingConfig accessConfig) { final NavigableRole namedCollectionRole = accessConfig.getNavigableRole(); - log.tracef( "Generating collection cache access: %s", namedCollectionRole ); + if ( L2CACHE_LOGGER.isTraceEnabled() ) { + L2CACHE_LOGGER.trace( "Generating collection cache access: " + namedCollectionRole ); + } return switch ( accessConfig.getAccessType() ) { case READ_ONLY -> generateReadOnlyCollectionAccess( accessConfig ); diff --git a/hibernate-core/src/main/java/org/hibernate/cache/spi/support/EntityReadOnlyAccess.java b/hibernate-core/src/main/java/org/hibernate/cache/spi/support/EntityReadOnlyAccess.java index fe3f0058fdeb..110e10cc9e3d 100644 --- a/hibernate-core/src/main/java/org/hibernate/cache/spi/support/EntityReadOnlyAccess.java +++ b/hibernate-core/src/main/java/org/hibernate/cache/spi/support/EntityReadOnlyAccess.java @@ -63,7 +63,7 @@ public boolean update( Object currentVersion, Object previousVersion) { // log.debugf( "Illegal attempt to update item cached as read-only [%s]", key ); - throw new UnsupportedOperationException( "Can't update readonly object" ); + throw new UnsupportedOperationException( "Can't update read-only object" ); } @Override @@ -75,6 +75,6 @@ public boolean afterUpdate( Object previousVersion, SoftLock lock) { // log.debugf( "Illegal attempt to update item cached as read-only [%s]", key ); - throw new UnsupportedOperationException( "Can't write to a readonly object" ); + throw new UnsupportedOperationException( "Can't write to a read-only object" ); } } From f0aa4d1aa0f61d3afd30b92fdebdb306ec05d704 Mon Sep 17 00:00:00 2001 From: Gavin King Date: Mon, 14 Jul 2025 12:54:16 +0200 Subject: [PATCH 31/32] LazyInitializationException probably shouldn't log from its constructor --- .../org/hibernate/LazyInitializationException.java | 13 ------------- 1 file changed, 13 deletions(-) diff --git a/hibernate-core/src/main/java/org/hibernate/LazyInitializationException.java b/hibernate-core/src/main/java/org/hibernate/LazyInitializationException.java index 775761898d45..035af0e229fe 100644 --- a/hibernate-core/src/main/java/org/hibernate/LazyInitializationException.java +++ b/hibernate-core/src/main/java/org/hibernate/LazyInitializationException.java @@ -4,12 +4,6 @@ */ package org.hibernate; -import org.hibernate.internal.CoreMessageLogger; - -import org.jboss.logging.Logger; - -import java.lang.invoke.MethodHandles; - /** * Indicates an attempt to access unfetched data outside the context * of an open stateful {@link Session}. @@ -25,12 +19,6 @@ */ public class LazyInitializationException extends HibernateException { - private static final CoreMessageLogger LOG = Logger.getMessageLogger( - MethodHandles.lookup(), - CoreMessageLogger.class, - LazyInitializationException.class.getName() - ); - /** * Constructs a {@code LazyInitializationException} using the given message. * @@ -38,7 +26,6 @@ public class LazyInitializationException extends HibernateException { */ public LazyInitializationException(String message) { super( message ); - LOG.trace( message, this ); } } From fe2893d0ab3431fa3d0ab7d95cb9ec5d7ee3a123 Mon Sep 17 00:00:00 2001 From: Gavin King Date: Mon, 14 Jul 2025 12:55:06 +0200 Subject: [PATCH 32/32] very minor cleanups --- .../hibernate/boot/archive/internal/ArchiveHelper.java | 4 ++-- .../boot/jaxb/internal/stax/LocalXmlResourceResolver.java | 2 +- .../org/hibernate/boot/model/relational/Namespace.java | 8 +------- .../org/hibernate/boot/spi/XmlMappingBinderAccess.java | 8 ++++---- 4 files changed, 8 insertions(+), 14 deletions(-) diff --git a/hibernate-core/src/main/java/org/hibernate/boot/archive/internal/ArchiveHelper.java b/hibernate-core/src/main/java/org/hibernate/boot/archive/internal/ArchiveHelper.java index 899cb3ea1f05..f118fdedd8d4 100644 --- a/hibernate-core/src/main/java/org/hibernate/boot/archive/internal/ArchiveHelper.java +++ b/hibernate-core/src/main/java/org/hibernate/boot/archive/internal/ArchiveHelper.java @@ -26,8 +26,8 @@ public class ArchiveHelper { private static final Logger log = Logger.getLogger( ArchiveHelper.class ); /** - * Get the JAR URL of the JAR containing the given entry - * Method used in a non managed environment + * Get the JAR URL of the JAR containing the given entry. + * Method used in a non-managed environment. * * @param url URL pointing to the known file in the JAR * @param entry file known to be in the JAR diff --git a/hibernate-core/src/main/java/org/hibernate/boot/jaxb/internal/stax/LocalXmlResourceResolver.java b/hibernate-core/src/main/java/org/hibernate/boot/jaxb/internal/stax/LocalXmlResourceResolver.java index 8b3d482a1988..80ddd3ab9acc 100644 --- a/hibernate-core/src/main/java/org/hibernate/boot/jaxb/internal/stax/LocalXmlResourceResolver.java +++ b/hibernate-core/src/main/java/org/hibernate/boot/jaxb/internal/stax/LocalXmlResourceResolver.java @@ -116,7 +116,7 @@ else if ( ConfigXsdSupport.cfgXsd().getNamespaceUri().matches( namespace ) ) { if ( systemID != null ) { // technically, "classpath://..." identifiers should only be declared as SYSTEM identifiers if ( systemID.startsWith( CLASSPATH_EXTENSION_URL_BASE ) ) { - log.tracef( "Recognized `classpath:` identifier; attempting to resolve on classpath [%s]", systemID ); + log.tracef( "Recognized 'classpath:' identifier; attempting to resolve on classpath [%s]", systemID ); final String path = systemID.substring( CLASSPATH_EXTENSION_URL_BASE.length() ); // todo : for this to truly work consistently, we need access to ClassLoaderService final InputStream stream = resolveInLocalNamespace( path ); diff --git a/hibernate-core/src/main/java/org/hibernate/boot/model/relational/Namespace.java b/hibernate-core/src/main/java/org/hibernate/boot/model/relational/Namespace.java index 28fdde23e2a3..4161a0827b7c 100644 --- a/hibernate-core/src/main/java/org/hibernate/boot/model/relational/Namespace.java +++ b/hibernate-core/src/main/java/org/hibernate/boot/model/relational/Namespace.java @@ -58,13 +58,7 @@ public Namespace(PhysicalNamingStrategy physicalNamingStrategy, JdbcEnvironment this.name = name; this.physicalName = physicalName( name, physicalNamingStrategy, jdbcEnvironment ); - if ( log.isTraceEnabled() ) { - log.tracef( - "Created database namespace [logicalName=%s, physicalName=%s]", - name.toString(), - physicalName.toString() - ); - } + log.tracef( "Created database namespace [logicalName=%s, physicalName=%s]", name, physicalName ); } private static Name physicalName(Name name, PhysicalNamingStrategy physicalNaming, JdbcEnvironment environment) { diff --git a/hibernate-core/src/main/java/org/hibernate/boot/spi/XmlMappingBinderAccess.java b/hibernate-core/src/main/java/org/hibernate/boot/spi/XmlMappingBinderAccess.java index da2a703ab9e5..896f6d1ee9c6 100644 --- a/hibernate-core/src/main/java/org/hibernate/boot/spi/XmlMappingBinderAccess.java +++ b/hibernate-core/src/main/java/org/hibernate/boot/spi/XmlMappingBinderAccess.java @@ -56,7 +56,7 @@ public MappingBinder getMappingBinder() { * Create a {@linkplain Binding binding} from a named URL resource */ public Binding bind(String resource) { - LOG.tracef( "reading mappings from resource : %s", resource ); + LOG.tracef( "Reading mappings from resource: %s", resource ); final Origin origin = new Origin( SourceType.RESOURCE, resource ); final URL url = classLoaderService.locateResource( resource ); if ( url == null ) { @@ -70,7 +70,7 @@ public Binding bind(String resource) { */ public Binding bind(File file) { final Origin origin = new Origin( SourceType.FILE, file.getPath() ); - LOG.tracef( "reading mappings from file : %s", origin.getName() ); + LOG.tracef( "Reading mappings from file: %s", origin.getName() ); if ( !file.exists() ) { throw new MappingNotFoundException( origin ); } @@ -81,7 +81,7 @@ public Binding bind(File file) { * Create a {@linkplain Binding binding} from an input stream */ public Binding bind(InputStreamAccess xmlInputStreamAccess) { - LOG.tracef( "reading mappings from InputStreamAccess : %s", xmlInputStreamAccess.getStreamName() ); + LOG.tracef( "Reading mappings from InputStreamAccess: %s", xmlInputStreamAccess.getStreamName() ); final Origin origin = new Origin( SourceType.INPUT_STREAM, xmlInputStreamAccess.getStreamName() ); final InputStream xmlInputStream = xmlInputStreamAccess.accessInputStream(); try { @@ -101,7 +101,7 @@ public Binding bind(InputStreamAccess xmlInputStr * Create a {@linkplain Binding binding} from an input stream */ public Binding bind(InputStream xmlInputStream) { - LOG.trace( "reading mappings from InputStream" ); + LOG.trace( "Reading mappings from InputStream" ); final Origin origin = new Origin( SourceType.INPUT_STREAM, null ); return new InputStreamXmlSource( origin, xmlInputStream, false ).doBind( getMappingBinder() ); }