From 10e17f12eaa097d1ebe0a40f28eceb170758b5ce Mon Sep 17 00:00:00 2001 From: Gavin King Date: Tue, 26 Aug 2025 18:30:19 +1000 Subject: [PATCH 1/5] very minor code cleanups in cfg package --- .../java/org/hibernate/cfg/Configuration.java | 29 ++++++++------- .../java/org/hibernate/cfg/Environment.java | 35 +++++++++---------- 2 files changed, 30 insertions(+), 34 deletions(-) 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 12d04dd1df71..0af085a7c064 100644 --- a/hibernate-core/src/main/java/org/hibernate/cfg/Configuration.java +++ b/hibernate-core/src/main/java/org/hibernate/cfg/Configuration.java @@ -23,7 +23,6 @@ import org.hibernate.MappingException; import org.hibernate.SessionFactory; import org.hibernate.SessionFactoryObserver; -import org.hibernate.boot.Metadata; import org.hibernate.boot.MetadataBuilder; import org.hibernate.boot.MetadataSources; import org.hibernate.boot.SessionFactoryBuilder; @@ -470,9 +469,9 @@ public Configuration configure(File configFile) throws HibernateException { * @param highlightSql should logged SQL be highlighted with pretty colors */ public Configuration showSql(boolean showSql, boolean formatSql, boolean highlightSql) { - setProperty( AvailableSettings.SHOW_SQL, Boolean.toString(showSql) ); - setProperty( AvailableSettings.FORMAT_SQL, Boolean.toString(formatSql) ); - setProperty( AvailableSettings.HIGHLIGHT_SQL, Boolean.toString(highlightSql) ); + setProperty( JdbcSettings.SHOW_SQL, Boolean.toString(showSql) ); + setProperty( JdbcSettings.FORMAT_SQL, Boolean.toString(formatSql) ); + setProperty( JdbcSettings.HIGHLIGHT_SQL, Boolean.toString(highlightSql) ); return this; } @@ -482,7 +481,7 @@ public Configuration showSql(boolean showSql, boolean formatSql, boolean highlig * @param action the {@link Action} */ public Configuration setSchemaExportAction(Action action) { - setProperty( AvailableSettings.HBM2DDL_AUTO, action.getExternalHbm2ddlName() ); + setProperty( SchemaToolingSettings.HBM2DDL_AUTO, action.getExternalHbm2ddlName() ); return this; } @@ -493,8 +492,8 @@ public Configuration setSchemaExportAction(Action action) { * @param pass the password */ public Configuration setCredentials(String user, String pass) { - setProperty( AvailableSettings.USER, user ); - setProperty( AvailableSettings.PASS, pass ); + setProperty( JdbcSettings.USER, user ); + setProperty( JdbcSettings.PASS, pass ); return this; } @@ -514,7 +513,7 @@ public Configuration setJdbcUrl(String url) { * @param jndiName the JNDI name of the datasource */ public Configuration setDatasource(String jndiName) { - setProperty( AvailableSettings.DATASOURCE, jndiName ); + setProperty( JdbcSettings.DATASOURCE, jndiName ); return this; } @@ -524,7 +523,7 @@ public Configuration setDatasource(String jndiName) { * @param transactionType the {@link PersistenceUnitTransactionType} */ public Configuration setTransactionType(PersistenceUnitTransactionType transactionType) { - setProperty( AvailableSettings.JAKARTA_TRANSACTION_TYPE, transactionType.toString() ); + setProperty( PersistenceSettings.JAKARTA_TRANSACTION_TYPE, transactionType.toString() ); return this; } @@ -783,8 +782,8 @@ public Configuration addAnnotatedClass(Class annotatedClass) { * * @return this (for method chaining) */ - public Configuration addAnnotatedClasses(Class... annotatedClasses) { - for (Class annotatedClass : annotatedClasses) { + public Configuration addAnnotatedClasses(Class... annotatedClasses) { + for ( var annotatedClass : annotatedClasses ) { addAnnotatedClass( annotatedClass ); } return this; @@ -814,7 +813,7 @@ public Configuration addPackage(String packageName) throws MappingException { * @throws MappingException in case there is an error in the mapping data */ public Configuration addPackages(String... packageNames) throws MappingException { - for (String packageName : packageNames) { + for ( String packageName : packageNames ) { addPackage( packageName ); } return this; @@ -1078,8 +1077,8 @@ public SessionFactory buildSessionFactory(ServiceRegistry serviceRegistry) throw .forEach( metadataBuilder::applyAttributeConverter ); } - final Metadata metadata = metadataBuilder.build(); - final SessionFactoryBuilder sessionFactoryBuilder = metadata.getSessionFactoryBuilder(); + final var metadata = metadataBuilder.build(); + final var sessionFactoryBuilder = metadata.getSessionFactoryBuilder(); if ( interceptor != null && interceptor != EmptyInterceptor.INSTANCE ) { sessionFactoryBuilder.applyInterceptor( interceptor ); @@ -1130,7 +1129,7 @@ public SessionFactory buildSessionFactory(ServiceRegistry serviceRegistry) throw public SessionFactory buildSessionFactory() throws HibernateException { log.trace( "Building session factory using internal StandardServiceRegistryBuilder" ); standardServiceRegistryBuilder.applySettings( properties ); - StandardServiceRegistry serviceRegistry = standardServiceRegistryBuilder.build(); + var serviceRegistry = standardServiceRegistryBuilder.build(); try { return buildSessionFactory( serviceRegistry ); } diff --git a/hibernate-core/src/main/java/org/hibernate/cfg/Environment.java b/hibernate-core/src/main/java/org/hibernate/cfg/Environment.java index eeea43cc61ea..93647fbeb30e 100644 --- a/hibernate-core/src/main/java/org/hibernate/cfg/Environment.java +++ b/hibernate-core/src/main/java/org/hibernate/cfg/Environment.java @@ -5,7 +5,6 @@ package org.hibernate.cfg; import java.io.IOException; -import java.io.InputStream; import java.lang.invoke.MethodHandles; import java.util.Properties; @@ -13,11 +12,12 @@ import org.hibernate.Internal; import org.hibernate.Version; import org.hibernate.internal.CoreMessageLogger; -import org.hibernate.internal.util.ConfigHelper; -import org.hibernate.internal.util.config.ConfigurationHelper; import org.jboss.logging.Logger; +import static org.hibernate.internal.util.ConfigHelper.getResourceAsStream; +import static org.hibernate.internal.util.config.ConfigurationHelper.maskOut; + /** * Provides access to configuration properties passed in {@link Properties} objects. *

@@ -141,30 +141,27 @@ public final class Environment implements AvailableSettings { GLOBAL_PROPERTIES = new Properties(); try { - InputStream stream = ConfigHelper.getResourceAsStream( "/hibernate.properties" ); - try { - GLOBAL_PROPERTIES.load(stream); - LOG.propertiesLoaded( ConfigurationHelper.maskOut( GLOBAL_PROPERTIES, PASS ) ); - } - catch (Exception e) { - LOG.unableToLoadProperties(); - } - finally { - try{ - stream.close(); + try (var stream = getResourceAsStream("/hibernate.properties")) { + try { + GLOBAL_PROPERTIES.load(stream); + LOG.propertiesLoaded( maskOut( GLOBAL_PROPERTIES, PASS ) ); } - catch (IOException ioe){ - LOG.unableToCloseStreamError( ioe ); + catch (Exception e) { + LOG.unableToLoadProperties(); } } + catch (IOException ioe) { + LOG.unableToCloseStreamError( ioe ); + } } catch (HibernateException he) { LOG.propertiesNotFound(); } try { - final Properties systemProperties = System.getProperties(); - // Must be thread-safe in case an application changes System properties during Hibernate initialization. + final var systemProperties = System.getProperties(); + // Must be thread-safe in case an application changes + // System properties during Hibernate initialization. // See HHH-8383. synchronized (systemProperties) { GLOBAL_PROPERTIES.putAll(systemProperties); @@ -187,7 +184,7 @@ private Environment() { * with all additional properties specified in {@code hibernate.properties}. */ public static Properties getProperties() { - final Properties copy = new Properties(); + final var copy = new Properties(); copy.putAll(GLOBAL_PROPERTIES); return copy; } From 1e81fef5fcd34ed17ab3b3a81b16fc50a80cf389 Mon Sep 17 00:00:00 2001 From: Gavin King Date: Tue, 26 Aug 2025 18:31:58 +1000 Subject: [PATCH 2/5] HHH-19738 mask out 'jakarta.persistence.jdbc.password' --- .../java/org/hibernate/cfg/Environment.java | 3 ++- .../util/config/ConfigurationHelper.java | 22 +++++++++++++++++-- 2 files changed, 22 insertions(+), 3 deletions(-) diff --git a/hibernate-core/src/main/java/org/hibernate/cfg/Environment.java b/hibernate-core/src/main/java/org/hibernate/cfg/Environment.java index 93647fbeb30e..7af51fc2874c 100644 --- a/hibernate-core/src/main/java/org/hibernate/cfg/Environment.java +++ b/hibernate-core/src/main/java/org/hibernate/cfg/Environment.java @@ -144,7 +144,8 @@ public final class Environment implements AvailableSettings { try (var stream = getResourceAsStream("/hibernate.properties")) { try { GLOBAL_PROPERTIES.load(stream); - LOG.propertiesLoaded( maskOut( GLOBAL_PROPERTIES, PASS ) ); + LOG.propertiesLoaded( maskOut( GLOBAL_PROPERTIES, + PASS, JAKARTA_JDBC_PASSWORD, JPA_JDBC_PASSWORD ) ); } catch (Exception e) { LOG.unableToLoadProperties(); diff --git a/hibernate-core/src/main/java/org/hibernate/internal/util/config/ConfigurationHelper.java b/hibernate-core/src/main/java/org/hibernate/internal/util/config/ConfigurationHelper.java index 6b032e3a45ab..6f17e53e8ff0 100644 --- a/hibernate-core/src/main/java/org/hibernate/internal/util/config/ConfigurationHelper.java +++ b/hibernate-core/src/main/java/org/hibernate/internal/util/config/ConfigurationHelper.java @@ -270,7 +270,7 @@ else if ( configurationValues instanceof Properties properties ) { } /** - * replace a property by a starred version + * Replace a property by a starred version * * @param props properties to check * @param key property to mask @@ -278,13 +278,31 @@ else if ( configurationValues instanceof Properties properties ) { * @return cloned and masked properties */ public static Properties maskOut(Properties props, String key) { - final Properties clone = (Properties) props.clone(); + final var clone = (Properties) props.clone(); if ( clone.get( key ) != null ) { clone.setProperty( key, "****" ); } return clone; } + /** + * Replace properties by starred version + * + * @param props properties to check + * @param keys properties to mask + * + * @return cloned and masked properties + */ + public static Properties maskOut(Properties props, String... keys) { + final var clone = (Properties) props.clone(); + for ( String key : keys ) { + if ( clone.get( key ) != null ) { + clone.setProperty( key, "****" ); + } + } + return clone; + } + /** * Extract a property value by name from the given properties object. *

From 80d157c1737f30d13f77d2f519b00c0ac97ccada Mon Sep 17 00:00:00 2001 From: Gavin King Date: Tue, 26 Aug 2025 21:27:24 +1000 Subject: [PATCH 3/5] cleanups in ConfigurationHelper --- .../util/config/ConfigurationHelper.java | 158 +++++++----------- 1 file changed, 62 insertions(+), 96 deletions(-) diff --git a/hibernate-core/src/main/java/org/hibernate/internal/util/config/ConfigurationHelper.java b/hibernate-core/src/main/java/org/hibernate/internal/util/config/ConfigurationHelper.java index 6f17e53e8ff0..a474851ebce5 100644 --- a/hibernate-core/src/main/java/org/hibernate/internal/util/config/ConfigurationHelper.java +++ b/hibernate-core/src/main/java/org/hibernate/internal/util/config/ConfigurationHelper.java @@ -5,7 +5,6 @@ package org.hibernate.internal.util.config; import java.util.HashMap; -import java.util.Iterator; import java.util.Locale; import java.util.Map; import java.util.Properties; @@ -14,8 +13,7 @@ import org.checkerframework.checker.nullness.qual.NonNull; import org.hibernate.Incubating; -import org.hibernate.boot.registry.StandardServiceRegistry; -import org.hibernate.cfg.AvailableSettings; +import org.hibernate.cfg.MappingSettings; import org.hibernate.dialect.Dialect; import org.hibernate.engine.config.spi.ConfigurationService; import org.hibernate.engine.jdbc.spi.JdbcServices; @@ -186,10 +184,10 @@ public static int getInt(String name, Map values, int defaultValue) { if ( value == null ) { return defaultValue; } - if (value instanceof Integer integer) { + else if (value instanceof Integer integer) { return integer; } - if (value instanceof String string) { + else if (value instanceof String string) { return Integer.parseInt(string); } throw new ConfigurationException( @@ -344,6 +342,10 @@ public static String extractPropertyValue(String propertyName, Map properti return value; } + /** + * @deprecated No longer used + */ + @Deprecated(since = "7.2", forRemoval = true) public static String extractValue( String name, Map values, @@ -374,10 +376,10 @@ public static String extractValue( @SuppressWarnings("rawtypes") @Deprecated(since = "7", forRemoval = true) public static Map toMap(String propertyName, String delim, Properties properties) { - Map map = new HashMap<>(); - String value = extractPropertyValue( propertyName, properties ); + final Map map = new HashMap<>(); + final String value = extractPropertyValue( propertyName, properties ); if ( value != null ) { - StringTokenizer tokens = new StringTokenizer( value, delim ); + final var tokens = new StringTokenizer( value, delim ); while ( tokens.hasMoreTokens() ) { map.put( tokens.nextToken(), tokens.hasMoreElements() ? tokens.nextToken() : "" ); } @@ -403,10 +405,10 @@ public static Map toMap(String propertyName, String delim, Properties properties @SuppressWarnings("rawtypes") @Deprecated(since = "7", forRemoval = true) public static Map toMap(String propertyName, String delim, Map properties) { - Map map = new HashMap<>(); - String value = extractPropertyValue( propertyName, properties ); + final Map map = new HashMap<>(); + final String value = extractPropertyValue( propertyName, properties ); if ( value != null ) { - StringTokenizer tokens = new StringTokenizer( value, delim ); + final var tokens = new StringTokenizer( value, delim ); while ( tokens.hasMoreTokens() ) { map.put( tokens.nextToken(), tokens.hasMoreElements() ? tokens.nextToken() : "" ); } @@ -440,12 +442,9 @@ public static String[] toStringArray(String propertyName, String delim, Properti */ public static String[] toStringArray(String stringForm, String delim) { // todo : move to StringHelper? - if ( stringForm != null ) { - return StringHelper.split( delim, stringForm ); - } - else { - return ArrayHelper.EMPTY_STRING_ARRAY; - } + return stringForm != null + ? StringHelper.split( delim, stringForm ) + : ArrayHelper.EMPTY_STRING_ARRAY; } /** @@ -454,13 +453,12 @@ public static String[] toStringArray(String stringForm, String delim) { * @param configurationValues The configuration map. */ public static void resolvePlaceHolders(Map configurationValues) { - final Iterator> itr = configurationValues.entrySet().iterator(); + final var itr = configurationValues.entrySet().iterator(); while ( itr.hasNext() ) { - final Map.Entry entry = itr.next(); - final Object value = entry.getValue(); - if ( value instanceof String string ) { + final var entry = itr.next(); + if ( entry.getValue() instanceof String string ) { final String resolved = resolvePlaceHolder( string ); - if ( !value.equals( resolved ) ) { + if ( !string.equals( resolved ) ) { if ( resolved == null ) { itr.remove(); } @@ -482,8 +480,8 @@ public static String resolvePlaceHolder(String property) { if ( !property.contains( PLACEHOLDER_START ) ) { return property; } - StringBuilder buff = new StringBuilder(); - char[] chars = property.toCharArray(); + final var result = new StringBuilder(); + final char[] chars = property.toCharArray(); for ( int pos = 0; pos < chars.length; pos++ ) { if ( chars[pos] == '$' ) { // peek ahead @@ -500,7 +498,7 @@ public static String resolvePlaceHolder(String property) { } } final String systemProperty = extractFromSystem( systemPropertyName ); - buff.append( systemProperty == null ? "" : systemProperty ); + result.append( systemProperty == null ? "" : systemProperty ); pos = x + 1; // make sure spinning forward did not put us past the end of the buffer... if ( pos >= chars.length ) { @@ -508,10 +506,9 @@ public static String resolvePlaceHolder(String property) { } } } - buff.append( chars[pos] ); + result.append( chars[pos] ); } - final String result = buff.toString(); - return result.isEmpty() ? null : result; + return result.isEmpty() ? null : result.toString(); } private static String extractFromSystem(String systemPropertyName) { @@ -523,96 +520,65 @@ private static String extractFromSystem(String systemPropertyName) { } } - @Incubating - public static synchronized int getPreferredSqlTypeCodeForBoolean(StandardServiceRegistry serviceRegistry) { - final Integer typeCode = serviceRegistry.requireService( ConfigurationService.class ).getSetting( - AvailableSettings.PREFERRED_BOOLEAN_JDBC_TYPE, - TypeCodeConverter.INSTANCE - ); + private static Integer getConfiguredTypeCode(ServiceRegistry serviceRegistry, String setting) { + final Integer typeCode = + serviceRegistry.requireService( ConfigurationService.class ) + .getSetting( setting, TypeCodeConverter.INSTANCE ); if ( typeCode != null ) { - INCUBATION_LOGGER.incubatingSetting( AvailableSettings.PREFERRED_BOOLEAN_JDBC_TYPE ); - return typeCode; + INCUBATION_LOGGER.incubatingSetting( setting ); } + return typeCode; + } - // default to the Dialect answer - return serviceRegistry.requireService( JdbcServices.class ) - .getJdbcEnvironment() - .getDialect() - .getPreferredSqlTypeCodeForBoolean(); + @Incubating + public static synchronized int getPreferredSqlTypeCodeForBoolean(ServiceRegistry serviceRegistry) { + final Integer typeCode = + getConfiguredTypeCode( serviceRegistry, MappingSettings.PREFERRED_BOOLEAN_JDBC_TYPE ); + return typeCode != null + ? typeCode + : serviceRegistry.requireService( JdbcServices.class ) + .getDialect().getPreferredSqlTypeCodeForBoolean(); } @Incubating public static synchronized int getPreferredSqlTypeCodeForBoolean(ServiceRegistry serviceRegistry, Dialect dialect) { - final Integer typeCode = serviceRegistry.requireService( ConfigurationService.class ).getSetting( - AvailableSettings.PREFERRED_BOOLEAN_JDBC_TYPE, - TypeCodeConverter.INSTANCE - ); - if ( typeCode != null ) { - INCUBATION_LOGGER.incubatingSetting( AvailableSettings.PREFERRED_BOOLEAN_JDBC_TYPE ); - return typeCode; - } - - // default to the Dialect answer - return dialect.getPreferredSqlTypeCodeForBoolean(); + final Integer typeCode = + getConfiguredTypeCode( serviceRegistry, MappingSettings.PREFERRED_BOOLEAN_JDBC_TYPE ); + return typeCode != null ? typeCode : dialect.getPreferredSqlTypeCodeForBoolean(); } @Incubating - public static synchronized int getPreferredSqlTypeCodeForDuration(StandardServiceRegistry serviceRegistry) { - final Integer explicitSetting = serviceRegistry.requireService( ConfigurationService.class ).getSetting( - AvailableSettings.PREFERRED_DURATION_JDBC_TYPE, - TypeCodeConverter.INSTANCE - ); - if ( explicitSetting != null ) { - INCUBATION_LOGGER.incubatingSetting( AvailableSettings.PREFERRED_DURATION_JDBC_TYPE ); - return explicitSetting; - } + public static synchronized int getPreferredSqlTypeCodeForDuration(ServiceRegistry serviceRegistry) { + final Integer explicitSetting = + getConfiguredTypeCode( serviceRegistry, MappingSettings.PREFERRED_DURATION_JDBC_TYPE ); + return explicitSetting != null ? explicitSetting : SqlTypes.DURATION; - return SqlTypes.DURATION; } @Incubating - public static synchronized int getPreferredSqlTypeCodeForUuid(StandardServiceRegistry serviceRegistry) { - final Integer explicitSetting = serviceRegistry.requireService( ConfigurationService.class ).getSetting( - AvailableSettings.PREFERRED_UUID_JDBC_TYPE, - TypeCodeConverter.INSTANCE - ); - if ( explicitSetting != null ) { - INCUBATION_LOGGER.incubatingSetting( AvailableSettings.PREFERRED_UUID_JDBC_TYPE ); - return explicitSetting; - } + public static synchronized int getPreferredSqlTypeCodeForUuid(ServiceRegistry serviceRegistry) { + final Integer explicitSetting = + getConfiguredTypeCode( serviceRegistry, MappingSettings.PREFERRED_UUID_JDBC_TYPE ); + return explicitSetting != null ? explicitSetting : SqlTypes.UUID; - return SqlTypes.UUID; } @Incubating - public static synchronized int getPreferredSqlTypeCodeForInstant(StandardServiceRegistry serviceRegistry) { - final Integer explicitSetting = serviceRegistry.requireService( ConfigurationService.class ).getSetting( - AvailableSettings.PREFERRED_INSTANT_JDBC_TYPE, - TypeCodeConverter.INSTANCE - ); - if ( explicitSetting != null ) { - INCUBATION_LOGGER.incubatingSetting( AvailableSettings.PREFERRED_INSTANT_JDBC_TYPE ); - return explicitSetting; - } + public static synchronized int getPreferredSqlTypeCodeForInstant(ServiceRegistry serviceRegistry) { + final Integer explicitSetting = + getConfiguredTypeCode( serviceRegistry, MappingSettings.PREFERRED_INSTANT_JDBC_TYPE ); + return explicitSetting != null ? explicitSetting : SqlTypes.TIMESTAMP_UTC; - return SqlTypes.TIMESTAMP_UTC; } @Incubating - public static synchronized int getPreferredSqlTypeCodeForArray(StandardServiceRegistry serviceRegistry) { - final Integer explicitSetting = serviceRegistry.requireService( ConfigurationService.class ).getSetting( - AvailableSettings.PREFERRED_ARRAY_JDBC_TYPE, - TypeCodeConverter.INSTANCE - ); - if ( explicitSetting != null ) { - INCUBATION_LOGGER.incubatingSetting( AvailableSettings.PREFERRED_ARRAY_JDBC_TYPE ); - return explicitSetting; - } - // default to the Dialect answer - return serviceRegistry.requireService( JdbcServices.class ) - .getJdbcEnvironment() - .getDialect() - .getPreferredSqlTypeCodeForArray(); + public static synchronized int getPreferredSqlTypeCodeForArray(ServiceRegistry serviceRegistry) { + final Integer explicitSetting = + getConfiguredTypeCode( serviceRegistry, MappingSettings.PREFERRED_ARRAY_JDBC_TYPE ); + return explicitSetting != null + ? explicitSetting + : serviceRegistry.requireService( JdbcServices.class ) + .getDialect().getPreferredSqlTypeCodeForArray(); } public static void setIfNotEmpty(String value, String settingName, Map configuration) { From 332cc3a5413e16c2b4df7dbbcb044e9722386c29 Mon Sep 17 00:00:00 2001 From: Gavin King Date: Tue, 26 Aug 2025 23:14:43 +1000 Subject: [PATCH 4/5] refactoring to SessionFactorySettings --- .../internal/SessionFactoryImpl.java | 8 +-- .../internal/SessionFactorySettings.java | 58 ++++++++++--------- .../util/config/ConfigurationHelper.java | 32 ++++++++-- 3 files changed, 60 insertions(+), 38 deletions(-) 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 f88d72715840..34050c7d2532 100644 --- a/hibernate-core/src/main/java/org/hibernate/internal/SessionFactoryImpl.java +++ b/hibernate-core/src/main/java/org/hibernate/internal/SessionFactoryImpl.java @@ -137,11 +137,9 @@ import static java.util.Collections.unmodifiableSet; import static org.hibernate.cfg.AvailableSettings.CURRENT_SESSION_CONTEXT_CLASS; import static org.hibernate.internal.FetchProfileHelper.addFetchProfiles; -import static org.hibernate.internal.SessionFactorySettings.deprecationCheck; import static org.hibernate.internal.SessionFactorySettings.determineJndiName; +import static org.hibernate.internal.SessionFactorySettings.getMaskedSettings; import static org.hibernate.internal.SessionFactorySettings.getSessionFactoryName; -import static org.hibernate.internal.SessionFactorySettings.getSettings; -import static org.hibernate.internal.SessionFactorySettings.maskOutSensitiveInformation; import static org.hibernate.jpa.HibernateHints.HINT_TENANT_ID; import static org.hibernate.proxy.HibernateProxy.extractLazyInitializer; import static org.hibernate.resource.jdbc.spi.PhysicalConnectionHandlingMode.DELAYED_ACQUISITION_AND_RELEASE_AFTER_STATEMENT; @@ -239,9 +237,7 @@ public SessionFactoryImpl( jdbcServices = serviceRegistry.requireService( JdbcServices.class ); - settings = getSettings( options, serviceRegistry ); - maskOutSensitiveInformation( settings ); - deprecationCheck( settings ); + settings = getMaskedSettings( options, serviceRegistry ); LOG.instantiatingFactory( uuid, settings ); sqlStringGenerationContext = createSqlStringGenerationContext( bootMetamodel, options, jdbcServices ); diff --git a/hibernate-core/src/main/java/org/hibernate/internal/SessionFactorySettings.java b/hibernate-core/src/main/java/org/hibernate/internal/SessionFactorySettings.java index b3235b272bcb..4f3eb6a350f1 100644 --- a/hibernate-core/src/main/java/org/hibernate/internal/SessionFactorySettings.java +++ b/hibernate-core/src/main/java/org/hibernate/internal/SessionFactorySettings.java @@ -5,9 +5,8 @@ package org.hibernate.internal; import org.hibernate.boot.cfgxml.spi.CfgXmlAccessService; -import org.hibernate.boot.cfgxml.spi.LoadedConfig; import org.hibernate.boot.spi.SessionFactoryOptions; -import org.hibernate.cfg.AvailableSettings; +import org.hibernate.cfg.JdbcSettings; import org.hibernate.engine.config.spi.ConfigurationService; import org.hibernate.query.sqm.mutation.internal.temptable.GlobalTemporaryTableStrategy; import org.hibernate.query.sqm.mutation.internal.temptable.LocalTemporaryTableStrategy; @@ -25,6 +24,7 @@ import static org.hibernate.engine.config.spi.StandardConverters.STRING; import static org.hibernate.internal.log.DeprecationLogger.DEPRECATION_LOGGER; import static org.hibernate.internal.util.StringHelper.isNotEmpty; +import static org.hibernate.internal.util.config.ConfigurationHelper.maskOut; /** * Helper methods used to set up a {@link SessionFactoryImpl}. @@ -33,7 +33,7 @@ class SessionFactorySettings { static Map getSettings( SessionFactoryOptions options, SessionFactoryServiceRegistry serviceRegistry) { - final Map settings = + final var settings = serviceRegistry.requireService( ConfigurationService.class ) .getSettings(); final Map result = new HashMap<>( settings ); @@ -48,6 +48,13 @@ static Map getSettings( return result; } + static Map getMaskedSettings( + SessionFactoryOptions options, SessionFactoryServiceRegistry serviceRegistry) { + final var settings = getSettings( options, serviceRegistry ); + deprecationCheck( settings ); + return maskOutSensitiveInformation( settings ); + } + static String getSessionFactoryName( SessionFactoryOptions options, SessionFactoryServiceRegistry serviceRegistry) { final String sessionFactoryName = options.getSessionFactoryName(); @@ -55,7 +62,7 @@ static String getSessionFactoryName( return sessionFactoryName; } - final LoadedConfig loadedConfig = + final var loadedConfig = serviceRegistry.requireService( CfgXmlAccessService.class ) .getAggregatedConfig(); if ( loadedConfig != null ) { @@ -65,32 +72,25 @@ static String getSessionFactoryName( } } - final ConfigurationService configurationService = - serviceRegistry.requireService( ConfigurationService.class ); - return configurationService.getSetting( PERSISTENCE_UNIT_NAME, STRING ); + return serviceRegistry.requireService( ConfigurationService.class ) + .getSetting( PERSISTENCE_UNIT_NAME, STRING ); } - static void maskOutSensitiveInformation(Map props) { - maskOutIfSet( props, AvailableSettings.JPA_JDBC_USER ); - maskOutIfSet( props, AvailableSettings.JPA_JDBC_PASSWORD ); - maskOutIfSet( props, AvailableSettings.JAKARTA_JDBC_USER ); - maskOutIfSet( props, AvailableSettings.JAKARTA_JDBC_PASSWORD ); - maskOutIfSet( props, AvailableSettings.USER ); - maskOutIfSet( props, AvailableSettings.PASS ); - } - - private static void maskOutIfSet(Map props, String setting) { - if ( props.containsKey( setting ) ) { - props.put( setting, "****" ); - } + static Map maskOutSensitiveInformation(Map props) { + return maskOut( props, + JdbcSettings.JPA_JDBC_USER, + JdbcSettings.JPA_JDBC_PASSWORD, + JdbcSettings.JAKARTA_JDBC_USER, + JdbcSettings.JAKARTA_JDBC_PASSWORD, + JdbcSettings.USER, + JdbcSettings.PASS ); } static String determineJndiName( String name, SessionFactoryOptions options, SessionFactoryServiceRegistry serviceRegistry) { - final ConfigurationService configService = - serviceRegistry.requireService( ConfigurationService.class ); + final var configService = serviceRegistry.requireService( ConfigurationService.class ); final String explicitJndiName = configService.getSetting( SESSION_FACTORY_JNDI_NAME, STRING ); if ( isNotEmpty( explicitJndiName ) ) { return explicitJndiName; @@ -100,13 +100,15 @@ else if ( options.isSessionFactoryNameAlsoJndiName() == Boolean.FALSE ) { return null; } else { - final String expliciSessionFactoryname = configService.getSetting( SESSION_FACTORY_NAME, STRING ); - if ( isNotEmpty( expliciSessionFactoryname ) ) { - return expliciSessionFactoryname; + final String explicitSessionFactoryName = configService.getSetting( SESSION_FACTORY_NAME, STRING ); + if ( isNotEmpty( explicitSessionFactoryName ) ) { + return explicitSessionFactoryName; + } + else { + final String unitName = configService.getSetting( PERSISTENCE_UNIT_NAME, STRING ); + // if name comes from JPA persistence-unit name + return !isNotEmpty( unitName ) ? name : null; } - final String unitName = configService.getSetting( PERSISTENCE_UNIT_NAME, STRING ); - // if name comes from JPA persistence-unit name - return ! isNotEmpty( unitName ) ? name : null; } } diff --git a/hibernate-core/src/main/java/org/hibernate/internal/util/config/ConfigurationHelper.java b/hibernate-core/src/main/java/org/hibernate/internal/util/config/ConfigurationHelper.java index a474851ebce5..1ecc02c83823 100644 --- a/hibernate-core/src/main/java/org/hibernate/internal/util/config/ConfigurationHelper.java +++ b/hibernate-core/src/main/java/org/hibernate/internal/util/config/ConfigurationHelper.java @@ -292,13 +292,37 @@ public static Properties maskOut(Properties props, String key) { * @return cloned and masked properties */ public static Properties maskOut(Properties props, String... keys) { - final var clone = (Properties) props.clone(); + Properties result = props; for ( String key : keys ) { - if ( clone.get( key ) != null ) { - clone.setProperty( key, "****" ); + if ( props.get( key ) != null ) { + if ( result == props ) { + result = (Properties) props.clone(); + } + result.setProperty( key, "****" ); } } - return clone; + return result; + } + + /** + * Replace properties by starred version + * + * @param props properties to check + * @param keys properties to mask + * + * @return cloned and masked properties + */ + public static Map maskOut(Map props, String... keys) { + Map result = props; + for ( String key : keys ) { + if ( props.containsKey( key ) ) { + if ( result == props ) { + result = new HashMap<>( props ); + } + result.put( key, "****" ); + } + } + return result; } /** From d290615f4fb77c95c401a27bffba1a30cb2f922c Mon Sep 17 00:00:00 2001 From: Gavin King Date: Wed, 27 Aug 2025 00:03:09 +1000 Subject: [PATCH 5/5] minor cleanups to SessionFactoryImpl --- .../internal/SessionFactoryImpl.java | 51 ++++++++----------- .../internal/SessionFactorySettings.java | 28 +++++++--- 2 files changed, 43 insertions(+), 36 deletions(-) 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 34050c7d2532..a239edceea41 100644 --- a/hibernate-core/src/main/java/org/hibernate/internal/SessionFactoryImpl.java +++ b/hibernate-core/src/main/java/org/hibernate/internal/SessionFactoryImpl.java @@ -59,7 +59,6 @@ import org.hibernate.dialect.Dialect; import org.hibernate.engine.jdbc.batch.spi.BatchBuilder; import org.hibernate.engine.jdbc.connections.spi.ConnectionProvider; -import org.hibernate.engine.jdbc.connections.spi.JdbcConnectionAccess; import org.hibernate.engine.jdbc.connections.spi.MultiTenantConnectionProvider; import org.hibernate.engine.jdbc.spi.JdbcServices; import org.hibernate.engine.profile.FetchProfile; @@ -453,13 +452,8 @@ private void disintegrate(Exception startupException, IntegratorObserver integra private SessionBuilderImpl createDefaultSessionOpenOptionsIfPossible() { final var tenantIdResolver = getCurrentTenantIdentifierResolver(); - if ( tenantIdResolver == null ) { - return withOptions(); - } - else { - //Don't store a default SessionBuilder when a CurrentTenantIdentifierResolver is provided - return null; - } + // Don't store a default SessionBuilder when a CurrentTenantIdentifierResolver is provided + return tenantIdResolver == null ? withOptions() : null; } private SessionBuilderImpl buildTemporarySessionOpenOptions() { @@ -817,16 +811,16 @@ public void close() { } if ( runtimeMetamodels != null && runtimeMetamodels.getMappingMetamodel() != null ) { - final JdbcConnectionAccess jdbcConnectionAccess = jdbcServices.getBootstrapJdbcConnectionAccess(); + final var jdbcConnectionAccess = jdbcServices.getBootstrapJdbcConnectionAccess(); runtimeMetamodels.getMappingMetamodel().forEachEntityDescriptor( entityPersister -> { - if ( entityPersister.getSqmMultiTableMutationStrategy() != null ) { - entityPersister.getSqmMultiTableMutationStrategy() - .release( this, jdbcConnectionAccess ); + final var mutationStrategy = entityPersister.getSqmMultiTableMutationStrategy(); + final var insertStrategy = entityPersister.getSqmMultiTableInsertStrategy(); + if ( mutationStrategy != null ) { + mutationStrategy.release( this, jdbcConnectionAccess ); } - if ( entityPersister.getSqmMultiTableInsertStrategy() != null ) { - entityPersister.getSqmMultiTableInsertStrategy() - .release( this, jdbcConnectionAccess ); + if ( insertStrategy != null ) { + insertStrategy.release( this, jdbcConnectionAccess ); } } ); @@ -960,7 +954,7 @@ public StatisticsImplementor getStatistics() { } public FilterDefinition getFilterDefinition(String filterName) { - final FilterDefinition filterDefinition = filters.get( filterName ); + final var filterDefinition = filters.get( filterName ); if ( filterDefinition == null ) { throw new UnknownFilterException( filterName ); } @@ -1088,7 +1082,7 @@ public static Interceptor configuredInterceptor(Interceptor interceptor, boolean } // prefer the SessionFactory-scoped interceptor, prefer that to any Session-scoped interceptor prototype - final Interceptor optionsInterceptor = options.getInterceptor(); + final var optionsInterceptor = options.getInterceptor(); if ( optionsInterceptor != null && optionsInterceptor != EmptyInterceptor.INSTANCE ) { return optionsInterceptor; } @@ -1140,20 +1134,20 @@ public SessionBuilderImpl(SessionFactoryImpl sessionFactory) { this.sessionFactory = sessionFactory; // set up default builder values... - final SessionFactoryOptions sessionFactoryOptions = sessionFactory.getSessionFactoryOptions(); - statementInspector = sessionFactoryOptions.getStatementInspector(); - connectionHandlingMode = sessionFactoryOptions.getPhysicalConnectionHandlingMode(); - autoClose = sessionFactoryOptions.isAutoCloseSessionEnabled(); - defaultBatchFetchSize = sessionFactoryOptions.getDefaultBatchFetchSize(); - subselectFetchEnabled = sessionFactoryOptions.isSubselectFetchEnabled(); - identifierRollback = sessionFactoryOptions.isIdentifierRollbackEnabled(); + final var options = sessionFactory.getSessionFactoryOptions(); + statementInspector = options.getStatementInspector(); + connectionHandlingMode = options.getPhysicalConnectionHandlingMode(); + autoClose = options.isAutoCloseSessionEnabled(); + defaultBatchFetchSize = options.getDefaultBatchFetchSize(); + subselectFetchEnabled = options.isSubselectFetchEnabled(); + identifierRollback = options.isIdentifierRollbackEnabled(); final var currentTenantIdentifierResolver = sessionFactory.getCurrentTenantIdentifierResolver(); if ( currentTenantIdentifierResolver != null ) { tenantIdentifier = currentTenantIdentifierResolver.resolveCurrentTenantIdentifier(); } - jdbcTimeZone = sessionFactoryOptions.getJdbcTimeZone(); + jdbcTimeZone = options.getJdbcTimeZone(); } @@ -1219,10 +1213,9 @@ public PhysicalConnectionHandlingMode getPhysicalConnectionHandlingMode() { @Override public String getTenantIdentifier() { - if ( tenantIdentifier == null ) { - return null; - } - return sessionFactory.getTenantIdentifierJavaType().toString( tenantIdentifier ); + return tenantIdentifier != null + ? sessionFactory.getTenantIdentifierJavaType().toString( tenantIdentifier ) + : null; } @Override diff --git a/hibernate-core/src/main/java/org/hibernate/internal/SessionFactorySettings.java b/hibernate-core/src/main/java/org/hibernate/internal/SessionFactorySettings.java index 4f3eb6a350f1..76176dabcc0d 100644 --- a/hibernate-core/src/main/java/org/hibernate/internal/SessionFactorySettings.java +++ b/hibernate-core/src/main/java/org/hibernate/internal/SessionFactorySettings.java @@ -116,19 +116,33 @@ static void deprecationCheck(Map settings) { for ( String setting:settings.keySet() ) { switch ( setting ) { case "hibernate.hql.bulk_id_strategy.global_temporary.create_tables": - DEPRECATION_LOGGER.deprecatedSetting( "hibernate.hql.bulk_id_strategy.global_temporary.create_tables", GlobalTemporaryTableStrategy.CREATE_ID_TABLES ); + DEPRECATION_LOGGER.deprecatedSetting( + "hibernate.hql.bulk_id_strategy.global_temporary.create_tables", + GlobalTemporaryTableStrategy.CREATE_ID_TABLES ); case "hibernate.hql.bulk_id_strategy.global_temporary.drop_tables": - DEPRECATION_LOGGER.deprecatedSetting( "hibernate.hql.bulk_id_strategy.global_temporary.drop_tables", GlobalTemporaryTableStrategy.DROP_ID_TABLES ); + DEPRECATION_LOGGER.deprecatedSetting( + "hibernate.hql.bulk_id_strategy.global_temporary.drop_tables", + GlobalTemporaryTableStrategy.DROP_ID_TABLES ); case "hibernate.hql.bulk_id_strategy.persistent.create_tables": - DEPRECATION_LOGGER.deprecatedSetting( "hibernate.hql.bulk_id_strategy.persistent.create_tables", PersistentTableStrategy.CREATE_ID_TABLES ); + DEPRECATION_LOGGER.deprecatedSetting( + "hibernate.hql.bulk_id_strategy.persistent.create_tables", + PersistentTableStrategy.CREATE_ID_TABLES ); case "hibernate.hql.bulk_id_strategy.persistent.drop_tables": - DEPRECATION_LOGGER.deprecatedSetting( "hibernate.hql.bulk_id_strategy.persistent.drop_tables", PersistentTableStrategy.DROP_ID_TABLES ); + DEPRECATION_LOGGER.deprecatedSetting( + "hibernate.hql.bulk_id_strategy.persistent.drop_tables", + PersistentTableStrategy.DROP_ID_TABLES ); case "hibernate.hql.bulk_id_strategy.persistent.schema": - DEPRECATION_LOGGER.deprecatedSetting( "hibernate.hql.bulk_id_strategy.persistent.schema", PersistentTableStrategy.SCHEMA ); + DEPRECATION_LOGGER.deprecatedSetting( + "hibernate.hql.bulk_id_strategy.persistent.schema", + PersistentTableStrategy.SCHEMA ); case "hibernate.hql.bulk_id_strategy.persistent.catalog": - DEPRECATION_LOGGER.deprecatedSetting( "hibernate.hql.bulk_id_strategy.persistent.catalog", PersistentTableStrategy.CATALOG ); + DEPRECATION_LOGGER.deprecatedSetting( + "hibernate.hql.bulk_id_strategy.persistent.catalog", + PersistentTableStrategy.CATALOG ); case "hibernate.hql.bulk_id_strategy.local_temporary.drop_tables": - DEPRECATION_LOGGER.deprecatedSetting( "hibernate.hql.bulk_id_strategy.local_temporary.drop_tables", LocalTemporaryTableStrategy.DROP_ID_TABLES ); + DEPRECATION_LOGGER.deprecatedSetting( + "hibernate.hql.bulk_id_strategy.local_temporary.drop_tables", + LocalTemporaryTableStrategy.DROP_ID_TABLES ); } } }